Junior — Middle
What methods are used to implement dependency injection in application components?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a way of passing dependencies (objects, services) into application components instead of creating them inside the component.
Main methods of dependency injection:
- Through constructor — dependencies are passed via constructor parameters. This is the preferred method because dependencies become mandatory and immutable.
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
}
- Through setters (setter methods) — dependencies are passed through special methods after the object is created.
public class Service {
private Repository repository;
public void setRepository(Repository repository) {
this.repository = repository;
}
}
- Through fields (field injection) — dependencies are injected directly into class fields, usually with annotations (e.g.,
@Autowiredin Spring).
public class Service {
@Autowired
private Repository repository;
}
Each method has its pros and cons; the choice depends on the context and the framework used.