Junior — Middle
What ways can dependency injection be implemented besides using constructors?
sobes.tech AI
Answer from AI
In addition to constructor-based dependency injection, the following methods can be used:
-
Setter Injection: dependencies are passed through setter methods. It allows changing dependencies after object creation.
-
Field Injection: dependencies are injected directly into class fields, usually with annotations (e.g., @Autowired in Spring).
-
Interface Injection: the class implements an interface that contains a method for passing the dependency.
Example of Setter Injection in Java:
public class Service {
private Repository repository;
public void setRepository(Repository repository) {
this.repository = repository;
}
public void perform() {
repository.doSomething();
}
}
Each method has its pros and cons; the choice depends on requirements for flexibility and testability of the code.