Spring inject without autowire annotation
Yes, example is correct (starting from Spring 4.3 release). According to the documentation (this for ex), if a bean has single constructor, @Autowired
annotation can be omitted.
But there are several nuances:
1. When single constructor is present and setter is marked with @Autowired
annotation, than both constructor & setter injection will be performed one after another:
@Component
public class TwoInjectionStyles {
private Foo foo;
public TwoInjectionStyles(Foo f) {
this.foo = f; //Called firstly
}
@Autowired
public void setFoo(Foo f) {
this.foo = f; //Called secondly
}
}
2. At the other hand, if there is no @Autowire
at all (as in your example), than f
object will be injected once via constructor, and setter can be used in it's common way without any injections.
From Spring 4.3 annotations are not required for constructor injection.
public class MovieRecommender {
private CustomerPreferenceDao customerPreferenceDao;
private MovieCatalog movieCatalog;
//@Autowired - no longer necessary
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
@Autowired
public setMovieCatalog(MovieCatalog movieCatalog) {
this.movieCatalog = movieCatalog;
}
}
But you still need @Autowired
for setter injection. I checked a moment ago with Spring Boot 1.5.7
(using Spring 4.3.11
) and when I removed @Autowired
then bean was not injected.