I have 2 components A and B. A depends on B. I wrote something like:
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
@Component
public class B {}
new XmlBeanFactory(new FileSystemResource("./spring.xml")).getBean(A.class);
config
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
<bean class="com.A" autowire="byType" />
It worked perfectly well. Now I want configure A by annotations too. So I add @Component annotation to A
@Component
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
And removed A description from configuration. So it just
<context:annotation-config/>
<context:component-scan
base-package="com">
</context:component-scan>
But B doesn’t injected anymore. Probably I should specify autowiring type or smt like that. So how I can fix it?
You have to use
ApplicationContextinstead of plainBeanFactory. Seems likeBeanFactorydoes not run post processors, including the one looking for@Autowiredannotation. I will try to find a piece of documentation for that, in the meantime try:BTW
@Autowiredis completely valid on setters, constructors, fields, etc. (source):