Saturday, March 8, 2014

Why you should autowire constructor instead of field or property

This is quite hot topic in blogs, just wanted to put short and clear list of arguments in favor of constructor injection.
  • Autowired field or property can not be used in constructor, need special callback method for that
  • Can not use final on autowired field or property
  • No separation of concerns. Code with autowired fields becomes Spring specific. Others don't support it.
  • Eliminating few lines of boilerplate required for constructor injection will not save you much time.
  • With field or property injection code becomes unreadable for those who are not familiar with IOC.
  • Field and property injection defeats purpose of constructor.
  • If constructor needs too many arguments, it's a sign for refactoring.
  • Most developers don't know all details of autowiring properties and fields and it's wrong to say that code becomes more readable.
  • Property and field injection hides dependencies instead of making them explicit.
Happy autowiring :)