What methods are used in Spring to implement dependency injection and which of them are considered correct?
sobes.tech AI
Answer from AI
In Spring, dependency injection (DI) is implemented in three main ways:
-
Through constructor — dependencies are passed to the class via its constructor. This is considered the most correct and recommended method, as it ensures immutability of dependencies and facilitates testing.
-
Through setters — dependencies are set via setter methods after the object is created. Suitable when dependencies are optional or can change.
-
Through field injection — dependencies are injected directly into the class fields using the
@Autowiredannotation. This method is less preferred, as it complicates testing and breaks encapsulation.
Example of constructor injection:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Thus, it is recommended to use constructor-based dependency injection to improve reliability and ease of testing.