Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
    Bookmark Topic Watch Topic
  • New Topic

Not sure about exact difference between Constructor Injection and Setter Injection

 
Maan Suraj
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Report post to moderator
I was going through this link below
http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/
Above, author gives couple of reasons why people use setter injection more than constructor injection. I was ok with first reason, but couldnt understand completely the second reason.
The second reason why setter injection is used a lot more often than you would expect, is the fact that frameworks like Spring in general, are much more suited to be configured by setter injection than by constructor injection. This is mostly because frameworks that need to be configured often contain lots of optional values. Making optional values configurable using constructor injection would lead to needless clutter and proliferating constructors, especially when used in combination with class inheritance.


Could anyone help me to understand above reason(I mean what is that optional values etc etc).
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
A setter method does not have to be called for your app to create instances. But with Constructor, you cannot create that object without its dependencies. With a setter method I can create that object without its dependencies. That makes them optional.




try creating a Mark without an OtherObject? You can't.

but with


You can with just new Mark();

Mark
 
Maan Suraj
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Report post to moderator
hmm..got it..thanks
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
jinesh parikh,
Your post was moved to a new topic.
This topic was marked as resolved over a year ago. You post has been moved to a new topic.
 
    Bookmark Topic Watch Topic
  • New Topic