aspose file tools*
The moose likes Spring and the fly likes Not sure about exact difference between Constructor Injection and Setter Injection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Frameworks » Spring
Reply locked New topic
Author

Not sure about exact difference between Constructor Injection and Setter Injection

Maan Suraj
Ranch Hand

Joined: Dec 20, 2007
Posts: 299
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).

Man Suraj
Someone says "Impossible is nothing". The man next him says "Let me see you licking your elbow tip!"
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17257
    
    6

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


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Maan Suraj
Ranch Hand

Joined: Dec 20, 2007
Posts: 299
hmm..got it..thanks
Bill Gorder
Bartender

Joined: Mar 07, 2010
Posts: 1666
    
    7

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.


[How To Ask Questions][Read before you PM me]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Not sure about exact difference between Constructor Injection and Setter Injection