Junior — Middle
What makes constructor-based dependency injection in Spring more preferable compared to other methods?
sobes.tech AI
Answer from AI
Constructor-based dependency injection in Spring is preferred because:
- Ensures immutability: All dependencies are set during object creation, making its state stable.
- Simplifies testing: Mock objects can be easily passed through the constructor.
- Explicitly shows dependencies: The constructor clearly indicates what the class depends on.
- Avoids issues with partially initialized objects: When using setters or fields, dependencies might not be set, leading to errors.
Example:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Here, UserService cannot be created without UserRepository, which guarantees correct initialization.