What dependency injection methods does the Spring Framework provide?
sobes.tech AI
Answer from AI
Spring Framework supports several methods of dependency injection (DI):
-
Constructor Injection — dependencies are passed through the class constructor parameters. This is the preferred method as it makes dependencies mandatory and simplifies testing.
-
Setter Injection — dependencies are set through setter methods after the object is created.
-
Field Injection — dependencies are injected directly into class fields using the
@Autowiredannotation. This method is less preferred due to testing complexity and encapsulation issues.
Example of constructor injection:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// methods
}
Spring automatically resolves dependencies and injects the required beans into components.
Spring also supports dependency injection via XML configuration, but in modern applications, annotations and Java configuration are more commonly used.