Spring Boot good practices
Reading material
- https://www.e4developer.com/2018/08/06/spring-boot-best-practices/
- https://medium.com/@raviyasas/spring-boot-best-practices-for-developers-3f3bdffa0090
Good practices
-
Keep your business logic free of Spring Boot code
With the lessons from the “Clear Architecture” in mind, you should also protect your business logic. It is very tempting to mix all sorts of Spring Boot code there… Don’t do it. If you resist the temptation, you will keep your business logic reusable.
It is common for parts of services to become libraries. These are much easier to create if you don’t have to remove a lot of Spring annotations from your code.
-
Use Spring Initializr for starting new Spring Boot projects
Creating your application with the Initializr ensures that you are picking up the tested and approved dependencies that will work well with Spring auto-configuration. You may even discover some new integrations that you were not aware exist.
-
Consider creating your own auto-configuration for common organizational concerns
-
Keep your @Controller’s clean and focused
-
Build your @Service’s around business capabilities
-
Make your database a detail – abstract it from the core logic
-
Favour Constructor Injection
-
Be familiar with the concurrency model
-
Externalise and mature your configuration management
-
Provide global exception handling
-
Use Spring profiles
-
Use a logging framework
-
Test your code
-
Use testing slices to make your testing easier and more focused
https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4
Testing code with Spring Boot can be tricky- you need to initialize your data layer, wire numerous services, mock things… It actually does not have to be that hard! The answer is- use testing slices.
With testing slices, you can wire-up only parts of your applications as necessary. That may save you a lot of time and ensure that your tests are not coupled to things that you are not using. There is a blog post titled Custom test slice with Spring Boot 1.4 from spring.io that explains that technique.