In my last post of Dependency Injection in Spring framework we saw what are possible ways of dependency injection and how we inject dependency. In this post we will see key differences between two type of dependence injection in spring framework.
Here are the differences between setter injection and constructor injection :-
- Use constructor inject when you want to strongly coupled the class.In above scenario if we have want address object to be created before employee than we can use constructor injection.Use setter injection when you want to loosely coupled the two objects.In setter injection,address object will get created then it will set the property of employee with address object.
- If both setter and constructor are used then setter injection will override constructor.If use Constructor injection. we have to inject dependence at time bean create.
- In Setter injection we can inject dependency later.i.e bean with incomplete dependencies.But it is not possible in case of constructor injection.If we are using constructor than we need to supply all dependencies i.e constructor enforce required dependencies.Constructor injection makes bean class object as immutable.
- In circular dependency case constructor injection throw exception ObjectCurrentlyInCreationException.
- In case of setter injection we can modify properties using setters method. It is not possible in case of constructor. Because every time a new object will be created.Which Mean we can make immutable bean using constructor injection.