1.2 Understanding IoC & DI
Dive deeper into Inversion of Control (IoC) and Dependency Injection (DI), the core ideologies of the Spring Framework.
1. Inversion of Control (IoC)
In traditional programming, the developer determines which objects to use, creates them (new), and controls the flow. In an environment where IoC is applied, the entity managing the program's flow shifts from the developer to the framework (Spring).
- Traditional Way: "I make the things (objects) I need myself."
- IoC Way: "I declare the functions (interfaces) I need, and someone (the container) brings them to me."
2. Dependency Injection (DI)
DI is one of the specific ways to implement IoC. It is a method where the dependencies between objects are configured and injected from the outside (by the Spring Container).
🚗 Car and Engine Analogy
Suppose a Car (Car) uses an Engine (Engine).
- Direct Creation: The car factory must know exactly how to manufacture the engine (Strong Coupling). If the engine changes, the entire car production process must be modified.
- Injection (DI): The car only defines the specification that it needs an "engine." An external entity (the assembly line) inserts the completed engine into the car (Loose Coupling).
3. Advantages of DI
- Loose Coupling: By lowering the dependency between classes, modifying one class has minimal impact on others.
- Increased Reusability: You can easily reuse code in different environments just by swapping out the dependent objects.
- Testability: It becomes very convenient to perform unit testing by injecting fake objects (Mocks) instead of real ones.
4. DI Methods in Spring
Spring primarily injects dependencies in the following ways:
- Constructor Injection: The most recommended way. Since dependencies are injected at the time of object creation, it ensures immutability.
- Setter Injection: Used when optional dependencies are needed.
- Field Injection: Directly injects into a field using
@Autowired. However, it is not recommended as it makes external changes difficult.
info
The core of DI is that "An object does not create its own parts but receives them from the outside."