Differentiate between constructor injection and setter injection - CodeByAkram

Differentiate between constructor injection and setter injection

Partial Dependency

In Setter Injection, partial dependency is possible, means if we have 4 dependencies as mentioned below,

Differentiate between constructor injection and setter injection, codebyakram


Then it is not necessary to inject all values if we are using setter injection.

But in Constructor Injection, partial dependency is not possible because we are calling the constructor of that class.

Overriding

Constructor Injection can not override the setter injected properties but Setter injection can override the constructor injected properties.

Changes

Setter injection makes bean class object as mutable but constructor injection makes bean class object as immutable. 

Number of dependencies

If we have dependencies for example 17 in our bean class then, in this case setter injection is not recommended as we need to write almost 17 setters right, bean length will increase.

In this case, Constructor injection is highly recommended, as we can inject all the dependencies with in 3 to 4 lines by calling one constructor.


No comments:

Post a Comment