Icon for gfsd IntelliJ IDEA

Spring Boot folder structure best practices

Best practices for structuring your folders in a Spring Boot project

In this post, we dive into the various aspects of creating a folder structure for your Spring Boot projects that is logical and easy to navigate for other members of your team.

Spring Boot is a popular choice for developing enterprise web applications in Java. With features like autoconfiguration, it provides an effective way of applying the Spring framework in your projects. To really take advantage of the efficiency gains that Spring Boot provides, there are a few best practices to adhere to.

🤓 New to Spring Boot?

Read our introduction to the Spring Boot framework!

In a collaborative development environment, keeping an organized and consistent folder structure is crucial so that any team member can navigate any part of the project without problems.

In this post, we’ll cover some of the key best practices for organizing folders in your Spring Boot projects!

Key principles of organizing Spring Boot projects

Setting up a sound Spring Boot folder structure is not rocket science. You’ll want to adhere to the following basic principles of organizing Spring Boot projects to support key aspects:

  • Clear structure: Define a clear folder structure with a transparent and logical layout. This helps others navigate your projects (e.g. find files, packages, resources, etc).
  • Modular approach & reusability: Your folder structure should mirror the modular approach of Spring Boot’s logical components. Things like controllers, services, repositories, configurations, and other elements should be located in a consistent way for easy navigation and to encourage reusing existing code when appropriate.
  • Maintainability & scalability: Make sure your folder structure can scale along with the growing needs of an expanding application. Keep the structure clean so as not to introduce technical debt, bugs, and regressions as the application evolves.
  • Support collaboration: Having a clear, sound, and standardized convention for organizing your project helps collaborate with other team members, especially as new members are being onboarded.
  • Testing: Place test classes and resources with their corresponding classes using a logical folder structure and naming convention to support debugging and testing.

🤔 Spring vs Spring Boot vs Spring Web MVC vs Spring WebFlux?

Check out our blog post: Understanding the Spring framework

Best practices for Spring Boot directory structuring

Use your build system’s default folder structure

Whether you’re using Maven, Gradle, or another build system, it’s a wise idea to continue using the standard structure built into these tools. This makes it easy for someone new to the project to navigate its structure.

The default structure looks similar for both Maven and Gradle:

src
|-- main
|   |-- java
|   |   `-- com
|   |       `-- symflower
|   |           `-- sampleapplication
|   |               `-- SampleApplication.java
|   |-- resources
|       |-- static
|       |-- templates
|       `-- application.properties
`-- test
    |-- java
    |   `-- com
    |       `-- symflower
    |           `-- sampleapplication
    |               `-- SampleApplicationTest.java
    `-- resources
        `-- application-test.properties

Separate by layers OR by feature

Some teams choose to set up a structure that’s consistent with the various layers of a Spring Boot application (e.g. service layer, repository layer, controller layer).

Others organize the codebase based on features. This way, there’s no need to switch between layers if you’re looking for all the classes relevant to a feature.

Weigh both options, choose one that your team agrees with, and then stick with that solution consistently throughout the project.

com
|-- example
|   `-- sampleapplication
|       |-- feature1
|       |   |-- Feature1Controller.java
|       |   |-- Feature1Service.java
|       |   `-- Feature1Repository.java
|       `-- feature2
|           |-- Feature2Controller.java
|           |-- Feature2Service.java
|           `-- Feature2Repository.java
`-- SampleApplication.java

Keep configuration files separate

It’s a good idea to create a separate folder for configuration files used to customize your application’s behavior (e.g. src/main/config or AppConfig for application-level configurations).

Use this folder to store application properties and YAML files that enable developers working with your code to configure logging, server ports, database connections, etc. This simplifies the management of multiple configurations for different environments.

src
|-- main
|   `-- config
|       |-- application.properties
|       `-- logback.xml
|-- test
    `-- resources
        `-- application-test.properties

Different folders and annotations for controllers, services, repositories & more

It’s a good idea to set up separate “Controllers”, “Services”, and “Repositories” folders.

  • “Controllers” will contain the classes that handle incoming HTTP requests and define API endpoints.
  • You’ll use “Services” to store all classes that implement the business logic of your application. For interfaces defined in the Services folder, you may want to set up a dedicated “Service implementors” directory
  • Classes responsible for interacting with a database (e.g. data access and persistence) will reside in the “Repositories” folder.

Make sure you also use Spring Boot’s annotations to identify classes as controllers (@RestController), services (@Service), or repositories (@Repository). You may want to create dedicated folders for classes related to application security (“Security”)

In addition to your code base being easier to navigate for humans, this has the added benefit of enabling Spring to detect these components automatically.

@Controller
@RequestMapping("/books")
public class BookController {
    @GetMapping("/first-match/{year}/{author}/{genre}")
    public Book getFirstMatchingBook(@PathVariable int year, @PathVariable String author, @PathVariable Genre genre){...}
    ...
}

public enum Genre {
    THRILLER,
    ...
}

Some teams even set up a “Utils” folder to store helper functions and utility classes. This helps reuse code for common tasks like data conversion, string manipulation, etc to support efficient application development.

Similarly, an “Enum” folder can come in handy to store enumerations (e.g. predefined constant values like status codes, types, etc). A “Models” folder helps store data models and entities that define how your application interacts with database tables or external sources of data.

Take advantage of Spring Boot’s modules

If you’re building a complex application with the contribution of multiple teams, it’s a good idea to use a modular structure. You can define modules and subprojects for various pieces of functionality or certain microservices within your application. This can help maintain a coherent structure while providing the independence needed to add components or test modules:

my-application
|-- library
|   |-- src
|       |-- main
|           |-- java
|           |-- resources
|       `-- test
|-- bookstore
|   |-- src
|       |-- main
|           |-- java
|           |-- resources
|       `-- test
|-- src
|   |-- main
|       |-- java
|       |-- resources
|   `-- test
`-- build.gradle

+1: Documentation

Not necessarily related to folder structure, but definitely a best practice: make sure to provide adequate documentation for your Spring Boot projects! Include comments as necessary, and create Javadoc or README files to help others navigate your codebase.

In the case of complex projects where it may not be self-explanatory, it may also make sense to document your folder structure. This will prove to be immensely valuable in the long run as the application grows, is maintained, and new team members add functionality or try to debug features.

Summary: how to create a sensible folder structure for your Spring Boot project?

Having all people in the project understand the intended folder structure helps maintain it in the long run.

As the project evolves and gradually turns into a legacy project, more and more new people join and the original writers may no longer be around. It then tends to happen that new developers add code in the wrong places. If you have a clear folder structure that is also well documented, then this is more unlikely to happen, making the project easier to maintain.

Sticking to these Spring Boot folder structure best practices will make sure you and other team members have a clear understanding of the project’s architecture. That can set a good foundation for collaboration, efficiency, and easy navigation of the code base going forward.

Looking for other Spring Boot best practices? Check out our post about the most powerful Best practices for testing Spring Boot applications!

Try Symflower in your IDE to generate unit test templates & test suites

Make sure you never miss any of our upcoming content by signing up for our newsletter and by following us on Twitter, LinkedIn or Facebook!

| 2024-03-09