Junior — Middle
What is the reason for not using the @Autowired annotation directly on fields in Spring?
sobes.tech AI
Answer from AI
Using the @Autowired annotation directly on fields in Spring is considered less preferable for several reasons:
- Testing complexity: Autowiring through fields makes it harder to create mock objects in unit tests, as fields are usually private and lack setters.
- Violation of the Inversion of Control (IoC) principle: Injecting dependencies via constructors or setters makes dependencies explicit, improving code readability and maintainability.
- Security and encapsulation: Autowiring through fields violates encapsulation, as dependencies are injected directly into private fields.
Therefore, it is recommended to use dependency injection via constructors or setters, which enhances testability and application architecture.
Example of constructor injection:
@Component
public class MyService {
private final Dependency dependency;
@Autowired
public MyService(Dependency dependency) {
this.dependency = dependency;
}
// ...
}