Spring Boot best practices
source link: https://marco.dev/spring-boot-best-practices/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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
- Olivier Gierke: why-field-injection-is-evil
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:
- Spring Boot: Type-safe Configuration Properties
Author
Marco Molteni
Marco Molteni Blog
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK