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.
- 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:
Minsko Hevery, Agile Coach at Google:
Richard Paul about testing these objects: