Author
DI - Constructor injection / Setter Injection ?
kri shan
Ranch Hand
Joined: Apr 08, 2004
Posts: 1303
What criteria we choose constructor injection or setter injection ?
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26499
Constructor injection is good when you want to force the caller to pass something and not default.
In practice, I tend to use a mix of the two. I use setter injection mainly when:
- Injecting more than one thing
- I don't control the constructor
- I'm only injecting for testing and the "real code" doesn't need to inject.
[Blog ] [JavaRanch FAQ ] [How To Ask Questions The Smart Way ] [Book Promos ]
Blogging on Certs: SCEA Part 1 , Part 2 & 3 , Core Spring 3 , OCAJP , OCPJP beta , TOGAF part 1 and part 2
Hong Anderson
Ranch Hand
Joined: Jul 05, 2005
Posts: 1936
posted Sep 03, 2009 22:26:18
0
Setter injection allows re-injecting. Constructor injection makes sure the client will get fully-configured object.
I prefer setter injection.
SCJA 1.0, SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJP 5.0, SCEA 5, SCBCD 5; OCUP - Fundamental, Intermediate and Advanced; IBM Certified Solution Designer - OOAD, vUML 2; SpringSource Certified Spring Professional
Dhanji Prasanna
author
Ranch Hand
Joined: Aug 30, 2009
Posts: 38
posted Sep 03, 2009 22:53:27
0
I spend several chapters on this subject =)
But the short of it is: prefer Constructor DI almost always, except when you have a circular reference to resolve.
Software Engineer at Google
http://twitter.com/dhanji
Hong Anderson
Ranch Hand
Joined: Jul 05, 2005
Posts: 1936
posted Sep 03, 2009 23:36:05
0
Dhanji Prasanna wrote:
But the short of it is: prefer Constructor DI almost always, except when you have a circular reference to resolve.
Could you please to give a short explanation why you prefer constructor DI?
Thanks.
subject: DI - Constructor injection / Setter Injection ?