Spring IOC (Inversion of Control)
November 8, 2024About 1 min
Spring IOC (Inversion of Control)
Spring IOC (Inversion of Control) is a design principle that delegates the responsibility of creating and managing objects to the Spring container. Simply put, IOC means that instead of creating dependencies on its own, an object’s dependencies are managed and injected by an external container like the Spring IOC container.
Core Concepts
IOC Container:
- The Spring IOC container is the core of the Spring framework. It manages the lifecycle of objects (beans) and their dependencies, with the configuration defined in XML or annotations.
- At the startup of the application, the container creates all required beans and injects them where needed.
Dependency Injection (DI):
- DI is an implementation of IOC, where an object's dependencies are injected externally rather than being created within the object itself.
- Spring supports common DI methods:
- Constructor Injection: Dependencies are passed through a constructor.
- Setter Injection: Dependencies are passed through setter methods.
How It Works
In traditional development, a class typically creates the dependencies it needs directly. For example, if class A
depends on class B
, it might look like this:
public class A {
private B b = new B();
}
With Spring IOC, class A doesn’t create B itself. Instead, the Spring container manages the creation of B and injects it into A. Now, A only declares that it needs a B instance:
Field Injection
Field Injection directly injects the dependency into the field, using the @Autowired annotation.
@Component
public class UserService {
@Autowired
private UserRepository userRepository;
}