Middle
What is Inversion of Control (IoC)?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a design principle where the control flow of a program is delegated to an external structure, typically a framework container, instead of obtaining dependencies directly in the code.
Key points:
- Delegation: The object does not create or seek its dependencies but receives them from outside.
- Container: IoC is usually implemented with a specialized container (e.g., Spring ApplicationContext, Guice Injector) that manages the lifecycle of objects and resolves dependencies.
- Reduced coupling: Objects become less dependent on specific implementations of other objects.
- Testability: Testing is simplified as mock objects can be easily substituted for dependencies.
- Extensibility: It is easier to introduce new implementations of dependencies without changing the code that uses them.
Common ways to implement IoC:
- Service Locator: The object explicitly requests dependencies from the Service Locator.
- Dependency Injection (DI): The most common method. Dependencies are provided to the object "from outside".
Examples of dependency injection (DI):
-
Constructor Injection:
// Dependency is provided via constructor public class MyClass { private final Dependency dependency; public MyClass(Dependency dependency) { this.dependency = dependency; } } -
Setter Injection:
// Dependency is provided via a setter method public class MyClass { private Dependency dependency; public void setDependency(Dependency dependency) { this.dependency = dependency; } } -
Field Injection:
// Dependency is injected directly into a field (often with annotations) public class MyClass { @Autowired // Example of Spring annotation private Dependency dependency; }
IoC, especially in the form of DI, is fundamental to many modern frameworks (Spring, Quarkus) and promotes the creation of loosely coupled, modular, and testable applications.