In Spring 3.X does a class have to be annotated as component in order to Autowire a field into it?
Let's say I have:
@Service("myBean")
public class Mybean {
}
public class Target {
@Autowired
@Qualifier("myBean")
private MyBean;
}
And then in my beans.xml
<context:component-scan base-package="com.package.beans" />
Where MyBean.java
is within com.package.beans.MyBean package
.
Does the class Target
have to be annotated as @Component
or some other spring annotation in order to autowire one of it's fields?
No, it doesn't have to be annotated, but it does have to be a Spring bean. You can do that by using a stereotype annotation such as @Component
, but you can also make a Spring bean by declaring a <bean>
element in your XML or by returning it from an @Bean
configuration method.
Note that it is preferable to use constructor injection in any case, as it makes no difference in autowiring but makes testing much easier and makes certain mistakes more difficult.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With