Setter Injection vs. Constructor Injection

Now we got a vast idea about setter injection and constructor injection with dependencies. let us see the difference between setter and constructor injection.

Setter Injection

 

Constructor Injection

1. With Setter Injection, the create instance might be there, but without all the required dependencies (as they have not been set through the setter). A user can use the object without setting de required dependencies.

 

1. When using Constructor Injection, all required dependencies should be provided through the constructor, as there should not be any setter, to inject them later on. So the instance has all required dependencies.

2. If we write setter and constructor injection for the same property, then Setter Injection will override the Constructor Injection.

 

2. But, constructor injection cannot override the setter injected values

3. If we have more dependencies, then setter injection is not recommended as bean length will increase.

 

3. In this case, Constructor injection is highly recommended.

4.  Bean class object as mutable

 

4. Bean class object as immutable


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext