Spring Boot best practices
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.
Avoid the use of @Value in Spring Boot
Spring Boot introduced the @ConfigurationProperties annotation that is 'far more superior than the basic @Value approach' according to Stéphane Nicoll (Pivotal).
- You inject only an object a POJO and not a list of fields
- There is less risk to do typos in the declaration of the property
- The POJO is TypeSafe and can contain complex structures (e.g. 'database.configuration.mysql.connection')
Here you can find the documentation:
- Spring Boot: Type-safe Configuration Properties