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:

Service service = new Service();
Controller controller = new Controller(service);

โ˜๏ธ You're manually creating objects and passing dependencies.

โœ… With IoC (Spring does this):

@Autowired
Controller controller;

๐Ÿ”„ 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

ย 

@Component
public class Controller {
ย  ย  private final Service service;

ย  ย  public Controller(Service service) {
ย  ย  ย  ย  this.service = service;
ย  ย  }
}

| Field Injection | Quick and easy (not recommended for testing) |

@Autowired
private Service service;

| Setter Injection | Used when dependency is optional |

@Autowired
public void setService(Service service) {
ย  ย  this.service = service;
}

๐Ÿง  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)
Back to blog

Leave a comment