Inversion of Control (IoC) & Dependency Injection
๐ Inversion of Control (IoC)
Inversion of Control means giving control to the framework (like Spring) to manage object creation and dependencies โ instead of writing that logic yourself.
๐ฆ Without IoC:
โ๏ธ You're manually creating objects and passing dependencies.
โ With IoC (Spring does this):
๐ Spring automatically:
- Creates the object
- Resolves and injects dependencies
๐ฏ This inversion of "who controls what" is called Inversion of Control.
๐งฉ Dependency Injection (DI)
Dependency Injection is a design pattern used to implement IoC.
It means: instead of a class creating its own dependencies, the framework injects them.
๐ Types of Dependency Injection in Spring:
Type | Example |
---|---|
Constructor | Preferred way |
| Field Injection | Quick and easy (not recommended for testing) |
| Setter Injection | Used when dependency is optional |
๐ง Summary
Concept | Meaning |
---|---|
IoC | Spring controls object creation and wiring |
Dependency Injection | Spring injects required objects into your class automatically |
โ Why It's Useful
- ๐ Reduces tight coupling
- ๐ง Improves testability
- ๐งผ Cleaner code with less boilerplate
- โป๏ธ Easy to swap components (e.g., switch DB layer)