Junior — Middle
How is the inversion of control (IoC) principle implemented in Spring?
sobes.tech AI
Answer from AI
In Spring, the principle of Inversion of Control (IoC) is implemented through the Spring IoC container, which manages the creation, configuration, and lifecycle of objects (beans). Instead of objects creating and wiring dependencies themselves, the container injects the necessary dependencies into objects using Dependency Injection.
For example, if a class depends on another class, Spring will automatically create and pass this dependency via constructor, setter, or fields based on configuration (annotations or XML).
Example with annotations:
@Component
public class Service {
private final Repository repository;
@Autowired
public Service(Repository repository) {
this.repository = repository;
}
}
@Component
public class Repository {
// ...
}
Here, Spring will create an instance of Repository and pass it to the Service constructor, ensuring inversion of control.