Work in progress, this post is still in ‘work in progress’ status
Avoid field and setter injection
It should be used only for optional dependencies or in test code.
- easy to use
- the bean can be changed runtime with a new call of the setter;
- the field can reference a null instance, you should add the annotation @Required to enforce the dependency;
- it’s easy to add dependencies, the class risk to violate the single responsibility principle becoming a container of services.
- Olivier Gierke: why-field-injection-is-evil
Use constructor injection
- the beans cannot be null;
- the object is immutable;
- the object can be defined final;
- in case the bean has only one constructor you can omit @Autowired;
- force to better think the responsibility of the class.
Use @Inject in place of @Autowired
- @Inject is compatible with other containers
- @Inject allows the declaration of injection points.