DEV Community

Phoenix
Phoenix

Posted on

IoC and DI

IoC and DI are the core principles that spring framework follows

Inversion of Control - It is a software design principle, in which the control of object creation and dependency management should be transferred from application code to framework or container.
It is just a guideline that says who takes the control of creation? but not how to imeplement it.
it just describes the way how objects are created. control of object creation should be shifted from application code to external entity or framework

IoC is just this rule:

A class must not decide or create the objects it depends on.

It does not say:

  • Who will create them
  • How they will be passed

It only says:

“The control must be outside the class.”

Dependency Injection - it is a design principle that implements IoC, where the dependencies are injected from outside through a framework, but not created by object itself.

It reduces coupling between objects as it is dynamically injected by framework.

Advantages of IoC and DI

  • Loose coupling - Don't have to change your code whenever the dependencies gets changed.
  • minimises the amount of code.
  • make unit testing very easy with different mock tests.
  • increased system maintainability and module reusability.
  • allows concurrent independent development.
  • replacing modules has no side-effects on other modules.
  • even if the requirements in future, we don't have to make lot of changes

Spring is called an IoC Container because it stores application objects and takes control of their creation, lifecycle, and dependency wiring instead of the application code.

using spring framework
we just define these are the dependencies of my class, during runtime execution the framework automatically creates this objects and injects them into this class.

Top comments (0)