Answer the question
In order to leave comments, you need to log in
Why is it recommended to use a constructor instead of the @Autowired annotation?
I recently started learning Spring and wondered why the community and the IDE itself recommend not to use @Autowired
Than this code:
private final EmployeeRepository repository;
EmployeeController(EmployeeRepository repository) {
this.repository = repository;
}
@Autowired
private EmployeeRepository repository;
Answer the question
In order to leave comments, you need to log in
type when testing. When you write a test, you will not forget to substitute objects. And so it doesn't really matter
I myself am still learning Spring.
First of all, I recommend reading the Spring in action book. It describes all the features of DI and their benefits.
1 - DI property
@Autowired
private SomeClass someClass
@Autowired
private final SomeClass someClass;
SomeService (SomeClass someClass) {
this.someClass = someClass;
}
@Autowired
@RequiredArgsConstructor
public class PageController {
private final SomeClass1 someClass1;
private final SomeClass2 someClass2;
private final SomeClass3 someClass3;
}
As for me, there is a significant difference between injection through a constructor and a setter. A constructor can hide immutable attributes of a class, a setter won't provide that, so it's not appropriate in cases like this. But constructor injection has a problem, it can create a circular dependency, which is not the case when using a setter. Also, the cyclic dependency during injection in the constructor can be fixed using the @Lazy annotation before the parameter that causes the dependency. These methods are used for different tasks. And I don’t like injections in the field at all, i.e. there is a kind of violation of encapsulation, you have a private field that is not networked either in the constructor or in the method, but the value is written there.
As far as I remember, from the documentation, Spring says - if it is possible, then it is better not to use the annotation and generally bind hard to Spring is not a good idea. Something in this spirit, as it were. Well, if it is logical to think, for example, there was some kind of update with these annotations, then your application will break, and if there are constructors, it is less likely that your application will break. Well, in general, something like this my young friend.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question