Junior — Middle
Besides using Spring, what are alternative methods of dependency injection in applications?
sobes.tech AI
Answer from AI
Besides Spring, inversion of control (IoC) can be implemented in the following ways:
- Using other frameworks, such as Google Guice — a lightweight DI container for Java.
- Manual dependency injection through constructors or setters without a framework.
- Using CDI (Contexts and Dependency Injection) — a Java EE standard for IoC.
- Applying factory methods and the Service Locator pattern for dependency management.
For example, with manual dependency injection, objects are created and passed explicitly:
class Service {
private final Repository repo;
public Service(Repository repo) {
this.repo = repo;
}
}
// In main or configuration
Repository repo = new Repository();
Service service = new Service(repo);
This is a simple way to achieve IoC without using Spring.