- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Constructor Injection and Setter Injection in Spring
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. | Key | Constructor based Injection | Setter 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>
Advertisements