aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes DI - Constructor injection / Setter Injection ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "DI - Constructor injection / Setter Injection ?" Watch "DI - Constructor injection / Setter Injection ?" New topic
Author

DI - Constructor injection / Setter Injection ?

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1367
What criteria we choose constructor injection or setter injection ?
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 29220
    
135

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
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
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
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: DI - Constructor injection / Setter Injection ?
 
Similar Threads
Dependency Injection with setter injection ?
how can i Pass an object from an Action to jsp page in struts?
Dependency checking and constructor injection
Is not autowire a another type of dependendcy injection?
DI Queries