Junior — Middle
What methods are used to implement dependency injection in code?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in Java can be implemented in several ways:
- Through constructor — dependencies are passed to the class constructor.
public class Service {
private final Repository repo;
public Service(Repository repo) {
this.repo = repo;
}
}
- Through setters (Setter Injection) — dependencies are set via setter methods.
public class Service {
private Repository repo;
public void setRepository(Repository repo) {
this.repo = repo;
}
}
-
Through interfaces (Interface Injection) — the class implements an interface that allows injecting dependencies.
-
Using DI frameworks — such as Spring Framework, Guice, which automatically manage creation and injection of dependencies via annotations (
@Autowired,@Inject) and configuration.
Example with Spring:
@Service
public class Service {
private final Repository repo;
@Autowired
public Service(Repository repo) {
this.repo = repo;
}
}
Thus, DI allows separating dependency creation from their usage, improving testability and modularity of the code.