Junior — Middle
Why is it preferable to implement dependency injection through the constructor in Spring?
sobes.tech AI
Answer from AI
Dependency injection through constructor in Spring is preferred for several reasons:
- Immutability of the object: All dependencies are set during object creation, making its state more predictable and safe.
- Mandatory dependencies: The constructor guarantees that all necessary dependencies are provided; otherwise, the object will not be created.
- Simplified testing: It is easy to manually create objects with the required dependencies in tests.
- No hidden dependencies: Injection through fields or setters can lead to dependencies being not obvious, whereas through the constructor they are explicitly visible.
Example of constructor injection:
@Component
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// methods
}