Spring
Setter vs Constructor Injection
Spring supports two types of dependency Injection, using setter method
e.g. setXXX() where XXX is dependency or via constructor argument. First
way of dependency injection is known
as setter injection while later is known as constructor injection.
Both approaches of Injecting dependency on Spring bean has there pros and
cons, which we will see in this Spring framework article. Difference between
Setter Injection and Constructor Injection in Spring is also a popular Spring framework interview question.Some time interviewer also ask as When do you use Setter Injection over Constructor
injection in Spring or simply benefits of using setter vs constructor injection
in Spring framework. Points discussed in this article not only help you to
understand Setter vs Constructor Injection but also Spring's dependency
Injection process. By the way if you are new in Spring framework and learning it, you may want to take a look at my list of 5 good books to learn Spring framework. That will certainly help on your learning process. Since Spring is now a must have skill for Java programmers, it worth putting time and effort to learn this powerful framework
Difference between Setter vs Constructor Injection in Spring http://t.co/pu4Q3F3ojw #java #springframework
— javinpaul (@javinpaul) May 22, 2015
Difference between Setter and Constructor Injection in Spring framework
1) Fundamental difference between setter and constructor injection, as
there name implies is How dependency is injected. Setter injection in Spring uses setter methods
like setDependency() to inject dependency on any bean managed by
Spring's IOC container. On the other hand constructor injection uses constructor to inject
dependency on any Spring managed bean.
2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses index to inject dependency, its not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.
3) Another difference between setter vs constructor injection in Spring and one of the drawback of setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.
4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call constructor, a new object is gets created.
5) One of our reader Murali Mohan Reddy, pointed out one more difference between Setter and Constructor injection in Spring, where later can help, if there is a circular dependency between two object A and B.
If Object A and B are dependent each other i.e A is depends ob B and vice-versa. Spring throws ObjectCurrentlyInCreationException while creating objects of A and B bcz A object cannot be created until B is created and vice-versa. So spring can resolve circular dependencies through setter-injection. Objects constructed before setter methods invoked.
When to use Setter Injection over Constructor Injection in Spring
Setter Injection has upper hand over Constructor Injection in terms of
readability. Since for configuring Spring we use XML files, readability is much
bigger concern. Also drawback of setter Injection around ensuring mandatory
dependency injected or not can be handled by configuring Spring to check
dependency using "dependency-check" attribute
of tag or tag.
Another worth noting point to remember while comparing Setter Injection vs
Constructor Injection is that, once number of dependency crossed a threshold
e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter
Injection is preferred choice when number of dependency to be injected is lot
more than normal, if some of those arguments is optional than using Builder design pattern is also
a good option.
In Summary both Setter Injection and Constructor Injection has there own advantage and disadvantage. Good thing about Spring is that it doesn't restrict you to use either Setter Injection or Constructor Injection and you are free to use both of them in one Spring configuration file. Use Setter injection when number of dependency is more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.
Further Reading on Spring Framework
- Spring Recipes: A Problem-Solution Approach By Gary Mak
- Expert Spring MVC and Web Flow By Seth Ladd, Darren Davison, Steven Devijver, and Colin Yates
Other Spring tutorials from Javarevisited Blog
- How to setup LDAP authentication in Java using Spring Security? (solution)
- How to limit maximum number of concurrent active session in Java web app? (demo)
- How to convert ArrayList to delimited String in Java using Spring? (solution)
- How to get ServletContext object in Spring controller? (example)
- 10 example of display tag in JSP and spring (examples)
- What is default bean scope in Spring MVC framework? (answer)
13 comments :
One of the principle which I follow to choose between Setter Injection vs Constructor Injection is principle of mandatory and optional, yeah It's What I call it :). If any dependency is mandatory for an Object to perform its duty then you should use Constructor Injection, having said that optional dependency can be injected using Setter injection. This technique gets best from both Setter and Constructor injection and its also good from maintenance point of view as it clearly high light which dependency is critical for object to work.
One more drawback is circular dependency when using constructor injection. Appreciated if you can add to your article.
@Molluru, Sure, but can you please elaborate this for our readers?
@Javin, Sure
If Object A and B are dependent each other i.e A is depends ob B and vice-versa. Spring throws ObjectCurrentlyInCreationException while creating objects of A and B bcz A object cannot be created until B is created and vice-versa. So spring can resolve circular dependencies through setter-injection. Objects constructed before setter methods invoked.
Thanks Murali, That make sense, but circular dependency is a not a good idea, and one should remove it altogether. I will include your comment in this article.
can any one exaplain point no-3 i.e how setter injection is that it does not ensures dependency Injection??
Once number of dependency crossed a threshold e.g. 5 or 6, it's NOT handy manageable to passing dependency via constructor. OR Once number of dependency crossed a threshold e.g. 5 or 6, it's handy manageable to passing dependency via constructor? Which one is true I mean If we have more dependencies,then which one is suitable - Setter DI & Constructor DI
Hi
I have the same questions which are raised by sarty and Rambabu Posa..
Could you please explain those..!
@Rambabu Posa and @Anonymous, once the number of dependency increases, it's become messy to pass them via constructor based injection. A better approach is to divide those dependency into two group of mandatory and optional, provide mandatory dependency via constructor injection and optional via setter based injection. One disadvantage of using setter-based dependency injection is that programmer is expected to take the responsibility of knowing the order on which dependency needs to be provided. In other word, setter-based dependency injection introduce risk of leaving object in half configured state.
The one and only reason for using Constructor injection is that it make dependency explicit and obvious. You know that in order to use a particular class, what other class you need to create. This makes it more testable as it's easy to mock a class which is required in constructor. On the other hand, when you use setter injection, dependency are some what hidden, it's not that obvious as it is in case of constructor, because constructor is historically used to create object. Now, it will not work well if you don't have a proper dependency injection constructor, otherwise any time you want to use a class, you need it's dependency to create it first. In short, use constructor injection to make obvious what dependency a class need to get it job done. For example
OrderProcess{
OrderProcessor(OrderQueue queue){
.....
}
}
here it's obvious that OrderProcessor needs an OrderQueue to work. In order to test this class, you can provide a mock of OrderQueue.
Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only.
did not get the Circular dependency matter.. how setter injection resolve this??
@Somitra, In case of circular dependency, spring doesn't let you to create object using constructor exception, but it does with setter injection.
Post a Comment