Constructor Injection vs Setter Injection
My opinion is that we should initialize an object by passing all collaborators in the constructor. That’s the Java natural way to initialize an object correctly. Other mechanisms such as Spring annotations (@Required) are artificial ways to achieve the same goal.
Why?
- Constructor-injection automatically enforces the order and completeness of the instantiated.In other words, it prevents the object to work with ‘null’ collaborators.
- Enforces the order of initialization and prevents circular dependencies
Are you insane? My constructor has lots of arguments!
If you have many collaborators in the constructor, that means your class may have too many responsabilities. That’s not a good practice. Remember the Single Responsability Principle. More than three is too many! Your tests will get complicated because you’ll have lots of different combinations to setup each scenario.
That doesn’t mean that in some situations we need to use setters (Legacy code and no time for refactoring?). In this case, use the @Required annotation to ensure Spring initializes all dependencies.
Information about this:
Spring Blog:
Minsko Hevery, Agile Coach at Google:
http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/
Richard Paul about testing these objects:
http://www.rapaul.com/2011/07/10/constructor-injection-unit-tests/
Great stuff, I didn’t know about the Spring blog post on this subject, it’s generally Spring code that has screeds and screeds of setter or reflection based injection. Cheers for the pingback.
Richard Paul
July 28, 2011 at 6:02 pm
[...] Alef – Setter injection versus constructor injection and the use of @Required Cuesta, Alex – Constructor Injection vs Setter Injection Hevery, Misko - Constructor Injection vs. Setter Injection [...]
Escolhendo entre injeção de dependências por construtores e injeção de dependências por setters « O rebolado de Turing
August 3, 2012 at 11:51 am
I think one should use Setter only for optional dependency as mentioned on How to choose between Setter vs Constructor dependency Injection
Javame
December 18, 2012 at 6:05 am