when to use setter or constructor injection in spring
Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such a case, if you want to pass information for only one property, it is possible by setter method only. Setter injection is using builder design patterns while creating objects so we can create an object without initializing all the properties of that object.
Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC containers will use the setter injection.
We can easily change the value by setter injection. It doesn't create a new bean instance always like a constructor. So setter injection is more flexible than constructor injection.
Another distinction between setter versus constructor injection in Spring and one of the disadvantages of setter injection is that it doesn't guarantee dependency injection. You can not ensure that specific dependency is injected or not, which implies you may have an item with inadequate dependency. Then again, constructor Injection doesn't permit you to build an object until your dependencies are prepared.
Setter Injection has advantage over Constructor Injection as far as meaningfulness. Since for configuring Spring we use XML files, comprehensibility is a lot greater concern. Additionally, a downside of setter Injection around guaranteeing required dependency injected or not can be dealt with by designing Spring to check dependency using "dependency-check" attribute of tag.
Using constructor injection we can avoid circular dependencies also. When two classes are dependent on each other and while creating the objects of class a or b spring ioc will not be able to understand which object has to be created first.
No comments: