• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DI - Constructor injection / Setter Injection ?

 
kri shan
Ranch Hand
Posts: 1462
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What criteria we choose constructor injection or setter injection ?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34208
341
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hong Anderson
Ranch Hand
Posts: 1936
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Setter injection allows re-injecting. Constructor injection makes sure the client will get fully-configured object.
I prefer setter injection.
 
Dhanji Prasanna
author
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hong Anderson
Ranch Hand
Posts: 1936
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic