Junior — Middle
What are the advantages of using constructor-based dependency injection in Spring?
sobes.tech AI
Answer from AI
Dependency injection through constructor in Spring has several advantages:
- Ensuring immutability: dependencies are passed during object creation and cannot be changed later, which increases code safety and predictability.
- Mandatory dependencies: if a dependency is not provided, the object will not be created, preventing errors related to missing necessary components.
- Simplified testing: mock objects or stubs can be easily substituted through the constructor when writing unit tests.
- Explicit declaration of dependencies: it is clear from the constructor what the class depends on, improving code readability and maintainability.
Example:
@Component
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// class methods
}