Reputation: 1043
I have the following beans:
Bean.java
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Bean {
private String arg;
}
Service.java
import lombok.Getter;
import javax.inject.Inject;
public class Service {
@Inject @Getter
private Bean bean;
private String arg;
public Service(String arg) {
this.arg = arg;
}
}
Here is how I instantiate those things:
test-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.example.Bean">
<constructor-arg value="bean param"/>
</bean>
<bean class="com.example.Service">
<constructor-arg value="service param"/>
</bean>
</beans>
But when I create the context and look what is inside Service
instance:
ApplicationContext context = new ClassPathXmlApplicationContext("test-context.xml");
System.out.println(context.getBean(Bean.class));
System.out.println(context.getBean(Service.class).getBean());
the second System.out
gives me null.
Why Bean
instance didn't get injected?
Upvotes: 0
Views: 1370
Reputation: 155
I'm not sure about your approach to mixing and matching XML config with annotations, it requires <context:annotation-config/>
. I'd say you'd be safer off doing it one way or the other. If you insist on using XML then inject the dependency in the XML definition
<bean id="foo" class="com.example.Bean">
<constructor-arg value="bean param"/>
</bean>
<bean class="com.example.Service">
<constructor-arg value="service param"/>
<property name="bean" ref="foo" />
</bean>
Alternatively do it all with annotations
@Component
public class Bean {
private String arg;
public Bean(@Value("{constructorArg}") final String arg) {
this.arg = arg;
}
}
@Service
public class Service {
@Autowired @Getter
private Bean bean;
private String arg;
public Service(@Value("{constructorArg}") String arg) {
this.arg = arg;
}
}
Upvotes: 1
Reputation: 1043
I've found the reason, I've just forgot <context:annotation-config/>
in order to make @Inject
annotation to work.
Upvotes: 2