Spring Boot best practices


Work in progress, this post is still in 'work in progress' status

@Autowired Injection

Avoid field and setter injection

It should be used only for optional dependencies or in test code.

Good

  • easy to use

Bad

  • 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.

References

Use constructor injection

Good

  • 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.

References

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).

The advantages:

  • 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:



WebApp built by Marco using SpringBoot, Java 17, Mustache, Markdown and in Azure