Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring does class have to be component to AutoWire a property in it?

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?

like image 569
Adam Bronfin Avatar asked Oct 30 '22 06:10

Adam Bronfin


1 Answers

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.

like image 165
chrylis -cautiouslyoptimistic- Avatar answered Nov 15 '22 05:11

chrylis -cautiouslyoptimistic-