Difference Between setter injection and Constructor injection
Now when should we go for Setter Injection and Constructor Injection?
Setter
Injection
|
Constructor
Injection
|
Setter injection performs injection after
creating bean class object so it is bit delayed injection.
|
Constructor injection perform injection
while creating bean class object so no delay in injection.
|
Supports cyclic dependency.
|
Doesn’t Supports cyclic dependency.
|
To perform setter injection on “n-properties”
in all angles “n-setter” method are required.
|
Ton perform constructor injection on n
properties in all angle n! Constructor is required.
|
If all properties are configured for setter
injection then container crates bean class object using 0-param constructor.
|
If any property is configured for constructor
injection container class object using parameterized constructor.
|
Partial dependency can be injected
using setter injection.
|
Partial dependency is Not possible by constructor injection.
|
Setter injection overrides the
constructor injection. If we use both constructor and setter
injection, IOC container will use the setter injection.
|
Vice-versa not possible.
|
We can easily change the value by
setter injection because It doesn't create a new bean instance.
So setter injection is flexible.
|
In case
of constructor injection it is not easy because it creates new instance for
each. So Constructor injection is not flexible.
|
Setter injection makes bean class object as
mutable [We can change].
|
Constructor injection makes bean class object
as immutable [We cannot change].
|
In case of setter injection we cannot assigned the value to
final field variable.
|
But in case of Constructor
injection we can assigned the value to final field variable.
|
One of the drawback of setter injection is
that it does not ensures dependency Injection which means you may have an object with incomplete
dependency.
|
On other hand constructor
Injection does not allow you to construct object, until your dependencies are
ready.
|
Now when should we go for Setter Injection and Constructor Injection?
- If bean class contains only one property or if all the properties of bean class should participate in dependency injection then go for constructor injection, because constructor injection is very faster than setter injection.
- If bean class contains more than one property and there is no need of making all properties participating in dependency injection, then we need to go for setter injection.