Junior — Middle
Can you explain how Spring implements the principle of inversion of control?
sobes.tech AI
Answer from AI
Spring implements the principle of Inversion of Control (IoC) through a Dependency Injection (DI) container. Instead of objects creating and managing their dependencies themselves, Spring takes on this task.
Main points:
- Spring Container creates objects (beans) and manages their lifecycle.
- Dependencies between objects are specified through configuration (annotations, XML, or Java configuration).
- Spring automatically injects dependencies into objects, for example, via constructors, setters, or fields.
Example with annotations:
@Component
public class ServiceA {
private final RepositoryB repositoryB;
@Autowired
public ServiceA(RepositoryB repositoryB) {
this.repositoryB = repositoryB;
}
}
@Component
public class RepositoryB {
// Implementation
}
Here, ServiceA does not create RepositoryB itself but receives it from Spring. This makes it easy to change implementations, improves testability, and reduces component coupling.
Thus, Spring reverses the management of dependencies from objects to the container, which is the essence of Inversion of Control.