Difference Between Constructor Injection and Setter Injection in Spring

SpringObject Oriented ProgrammingProgramming

Dependency Injection is a practice to pass dependent object to other objects. Spring has two types of Dependency Injection :

  • Constructor based Injection -When container call the constructor of the class. It should be used for mandatory dependencies.

Let’s say Class X is tightly  dependent on Class Y then we should use constructor based injection.  

  • Setter based Injection - It can be used by calling setter methods on your beans. It should be used for optional dependencies.

Both types of injection has their own pros and cons. Below is a list of some differences −

Sr. No.KeyConstructor based InjectionSetter based Injection
1
Circular
It doesn’t allow to create circular dependency
It doesn’t check the circular dependency
2
Ordering
Constructor-based DI fixes the order in which the dependencies need to be injected.
Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time.
3
MutilThread Environment  
Combining with final fields, constructor injection gives extra safety in multithreaded environment
No extra benefit in setter injection
4
Spring Code generation Library
Spring code generation library doesn’t support constructor injection so it will not be able to create proxy. It will force you to use no-argument constructor.  
Spring framework level code uses setter injection
5
Use Case
It should be used for mandatory dependencies
It should be used for optional dependencies.

Example of Constructor Injection

public class ConstructorInjectionExample {
   public ConstructorInjectionExample(BaseExmp baseExmp) {
      // ...
   }
}
<beans>
   <bean id = "ConstructorInjectionExample" class = "x.y.ConstructorInjectionExample">
   <constructor-arg ref = "baseExmp"/>
</bean>

<bean id = "baseExmp" class = "x.y.BaseExmp"/>

</beans>

Example of Setter Injection

public class SetterInjectionExample {

   public void setBaseExmp(BaseExmp baseExmp) {
      this.baseExmp = baseExmp;
   }
}
<beans>
   <bean id = "setterInjectionExample" class = "x.y.SetterInjectionExample">
   <property name = "baseExmp" ref = "baseExmp"/>
</bean>

</beans>
raja
Published on 09-Sep-2020 12:18:27
Advertisements