Junior — Middle
How can the IoC principle be implemented for dependency management in an application?
sobes.tech AI
Answer from AI
The principle of Inversion of Control (IoC) for dependency management in an application can be implemented using Dependency Injection (DI). This means that objects do not create their dependencies themselves but receive them from outside, usually through a constructor, setter, or interface.
In Java, this is often implemented with frameworks such as the Spring Framework, where the container manages the lifecycle of objects and their dependencies. An example of constructor injection:
public class Service {
private final Repository repository;
// Dependency is passed from outside
public Service(Repository repository) {
this.repository = repository;
}
public void doWork() {
repository.save();
}
}
// Dependency is created and passed elsewhere
Repository repo = new RepositoryImpl();
Service service = new Service(repo);
Thus, the creation and binding of objects are delegated to an external container or code, which increases modularity, testability, and flexibility of the application.