Junior — Middle
What methods are used to implement dependency injection in the Spring framework?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in the Spring Framework is primarily achieved through three methods:
-
Constructor Injection — dependencies are passed through the class constructor parameters. This is the most recommended method as it allows creating immutable objects and simplifies testing.
-
Setter Injection — dependencies are set via setter methods after the object is created.
-
Field Injection — dependencies are directly injected into class fields using the
@Autowiredannotation. This method is less preferred due to testing complexity and weak encapsulation.
Example of constructor-based dependency injection:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// class methods
}
Spring will automatically create and inject the required UserRepository bean when creating UserService.