Dependency Injection and Inversion of Control

In software development especially java the objects are dependent on other object, and traditionally there were ways to manage object creation, factory pattern and decorator pattern are name the few practices.

Currently the IOC and DI titles holds their place whenever anyone wants to explain about dependent objects.
Spring framework came up with the implementation of “Inversion Of Control” which is “Dependency Injection”

The Inversion of control(IOC) is a design concept and DI is implementation for Inversion of Control.

As per the spring documentation IoC is also known as dependency injection (DI)
lets talk about this in brief :

1 Dependency Injection
2 DI Types.
3 which to use when constructor based DI or setter based DI ?
4 Summary

2.1 Dependency Injection :
The dependency injection is a process where objects defines their dependencies and then container injects the bean to dependent class when it’s required.

DI is process of providing dependencies and IOC is the end result of DI.

1. Type of DI
DI exists in two major variants,
Constructor-based dependency injection and
Setter-based dependency injection.

3.which to use when constructor based DI or setter based DI ?
We can mix the Constructor based dependencies and setter- based dependencies.
it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a required dependency.

In case of circular dependency we can use the setter injection.

4.Summary :
The IOC is a design pattern and DI is implementation of DI.We can you both as we want but its a practice that if we need a mandatory dependencies then go for constructor dependencies and for optional dependencies use setter methods.

references :
Spring Documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *