Middle
What dependency injection methods are available in Spring? Which is preferred?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in Spring can be implemented in three main ways:
-
Through constructor — dependencies are passed via constructor parameters. This allows creating immutable objects and simplifies testing.
-
Through setters — dependencies are set via setter methods after object creation.
-
Through field injection — dependencies are directly injected into class fields using annotations.
Constructor injection is preferred because it provides:
- Explicit declaration of all dependencies
- Immutability of the object after creation
- Ease of testing and maintaining the code
Example of constructor injection:
@Component
public class Service {
private final Repository repository;
@Autowired
public Service(Repository repository) {
this.repository = repository;
}
}