Reputation: 15812
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?
Upvotes: 4
Views: 3388
Reputation: 341003
You have to use ApplicationContext
instead of plain BeanFactory
. Seems like BeanFactory
does not run post processors, including the one looking for @Autowired
annotation. I will try to find a piece of documentation for that, in the meantime try:
new ClassPathXmlApplicationContext("/spring.xml").getBean(B.class);
BTW @Autowired
is completely valid on setters, constructors, fields, etc. (source):
Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
Upvotes: 5
Reputation: 12774
I think you should try
@Component
public class A {
@Autowired
private B b;
}
}
@Component
public class B {}
You can refer to example on below link: http://www.roseindia.net/tutorial/spring/spring3/ioc/autoscanig.html
Upvotes: 0