Junior — Middle
What are the methods of dependency injection within the Spring Framework?
sobes.tech AI
Answer from AI
In the Spring Framework, dependency injection (DI) can be implemented using the following main methods:
- Through constructor — dependencies are passed via the class constructor parameters. This is the most recommended way, as it makes dependencies explicit and facilitates testing.
@Component
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
}
- Through setters (Setter Injection) — dependencies are set via setter methods after the object is created.
@Component
public class Service {
private Repository repository;
@Autowired
public void setRepository(Repository repository) {
this.repository = repository;
}
}
- Through fields (Field Injection) — dependencies are injected directly into fields using the
@Autowiredannotation.
@Component
public class Service {
@Autowired
private Repository repository;
}
This method is less preferred because it makes testing more difficult and violates the inversion of control principle.
All these methods are supported by Spring and allow flexible management of component dependencies.