Junior — Middle
Can you explain the concept of dependency injection in Java and how it is applied?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a pattern that allows objects to receive their dependencies from outside rather than creating them internally. In Java, this helps make the code more modular, testable, and maintainable.
Example: instead of a class creating a dependency object inside itself, it receives it through a constructor or setter.
public class Service {
private Repository repository;
// Injecting dependency via constructor
public Service(Repository repository) {
this.repository = repository;
}
public void doWork() {
repository.save();
}
}
// When creating a Service object, we pass the required Repository implementation
Repository repo = new DatabaseRepository();
Service service = new Service(repo);
In Java, frameworks like Spring are often used, which automatically manage the creation and injection of dependencies, simplifying development.