Spring input without auto-increment annotation

I find the answer: stack overflow dependency injection. No comments like @Autowired , @Inject or @Resource . TwoInjectionStyles that in this example there is no XML configuration TwoInjectionStyles bean (except for the simple <context:component-scan base-package="com.example" /> .

Is it correct to enter without annotation?

+5
source share
2 answers

From Spring 4.3, annotations are not required to embed a constructor.

 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 to inject the setter. I checked a moment ago with Spring Boot 1.5.7 (using Spring 4.3.11 ), and when I uninstalled @Autowired , then the bean was not introduced.

+6
source

Yes, the example is correct (starting with Spring 4.3). According to the documentation ( this for ex), if the bean has a single constructor, the @Autowired annotation may be omitted.

But there are several nuances:

1. If there is only one constructor, and the installer is marked with @Autowired annotation, then both the installation of the constructor and the installation 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. On the other hand, if there is no @Autowire at all (as in your example ), than f object will be entered once through the constructor, and the setter can be used in it in the usual way without any injections.

+4
source

Source: https://habr.com/ru/post/1272275/


All Articles