1. Overview
When building a new Spring Boot project, there’s a high degree of flexibility on how we can organize our classes.
Still, there are some recommendations that we need to keep in mind.
2. No Default Package
Given the fact that Spring Boot annotations like @ComponentScan, @EntityScan, @ConfigurationPropertiesScan and @SpringBootApplication use packages to define scanning locations, it’s recommended that we avoid using the default package — that is, we should always declare the package in our classes.
3. Main Class
The @SpringBootApplication annotation triggers component scanning for the current package and its sub-packages. Therefore, a solid way to go is to have the main class of the project reside in the base package.
This is configurable, and we can still locate it elsewhere by specifying the base package manually. However, in most cases, this option is certainly simpler.
Even more, a JPA-based project would need to have a few additional annotations on the main class:
@SpringBootApplication(scanBasePackages = "example.baeldung.com")
@EnableJpaRepositories("example.baeldung.com")
@EntityScan("example.baeldung.com")
Also, be aware that extra configuration might be needed.
4. Design
The design of the package structure is independent of Spring Boot. Therefore, it should be imposed by the requirements of our project.
One popular strategy is package-by-feature, which enhances modularity and enables package-private visibility inside sub-packages.
Let’s take, for example, the PetClinic project. This project was built by Spring developers to illustrate their view on how a common Spring Boot project should be structured.
It’s organized in a package-by-feature manner. Hence, we have the main package, org.springframework.samples.petclinic, and 5 sub-packages:
- org.springframework.samples.petclinic.model
- org.springframework.samples.petclinic.owner
- org.springframework.samples.petclinic.system
- org.springframework.samples.petclinic.vet
- org.springframework.samples.petclinic.visit
Each of them represents a domain or a feature of the application, grouping highly-coupled classes inside and enabling high cohesion.
5. Conclusion
In this small article, we had a look at some recommendations we need to keep in mind when building a Spring Boot project – and learned about how we can design the package structure.