00:00

Spring Boot Project Structure

Last updated:

A good Spring Boot project structure makes an application easy to read, easy to test and safe to grow. Spring Boot does not force a layout, but it does make two assumptions: your code follows the standard Maven or Gradle folders, and every class Spring should find lives in or below the package of your main class. Get those right and organize the packages sensibly, and a new team member can find any class in seconds.

This tutorial explains each folder in a Spring Boot project, why the root package matters, how to choose between organizing by layer and by feature, where configuration, static files and tests go, and when to split a project into several modules. It ends with a complete recommended layout for a shop application.

1. What Is a Spring Boot Project Structure?

The project structure is how files are arranged on disk: the build file, the source folders, the Java packages and the resource files. It has two levels:

  • Folder level: fixed by convention. Maven and Gradle expect src/main/java, src/main/resources and src/test/java, and Spring Boot reads resources from the classpath built from them.
  • Package level: your decision. How you group classes into packages decides how easy the code is to navigate and how well its parts stay separate.
Analogy: The folders are the rooms of a house, which every house has. The packages are how you arrange things inside the rooms. You can put all the cups in one cupboard and all the plates in another (by layer), or keep everything for breakfast together (by feature). Both work in a small kitchen; one works much better in a big one.

2. The Standard Folder Layout

A project generated by Spring Initializr looks like this:

Project layout
shop/
├── pom.xml                        build file (or build.gradle.kts)
├── mvnw, mvnw.cmd, .mvn/          Maven wrapper: builds without a local Maven install
├── compose.yaml                   optional: local services for Docker Compose support
└── src/
    ├── main/
    │   ├── java/
    │   │   └── com/javabytechie/shop/
    │   │       └── ShopApplication.java
    │   └── resources/
    │       ├── application.properties
    │       ├── static/            files served as-is: CSS, JS, images
    │       └── templates/         server-side templates, for example Thymeleaf
    └── test/
        └── java/
            └── com/javabytechie/shop/
                └── ShopApplicationTests.java
Folder or filePurposeEnds up in the JAR?
src/main/javaProduction Java codeYes, compiled to BOOT-INF/classes
src/main/resourcesConfiguration, templates, static files, SQL migrationsYes, copied to BOOT-INF/classes
src/test/javaUnit and integration testsNo
src/test/resourcesTest-only configuration and dataNo
target/ or build/Build outputIt is where the JAR is created; never commit it

3. The Root Package and the Main Class

Put the class with @SpringBootApplication in the root package, the top package of your application, for example com.javabytechie.shop. Every other class goes in that package or below it.

The reason is that @SpringBootApplication uses the main class's package as the starting point for two searches: component scanning, which finds your @Service and @RestController classes, and auto-configuration packages, which tell Spring Data where to look for repositories and JPA entities.

Correct and incorrect placement
com.javabytechie.shop.ShopApplication          <- main class in the root package
com.javabytechie.shop.catalog.ProductService   <- found (sub-package)
com.javabytechie.shop.order.OrderController    <- found (sub-package)
com.javabytechie.common.MoneyFormatter         <- NOT found (sibling package)
Avoid the default package. If the main class has no package statement, Spring Boot logs a warning that the application context is unlikely to start, because it would try to scan every class on the classpath, including all libraries.

4. Package by Layer vs Package by Feature

There are two common ways to group classes below the root package.

Package by layer compared with package by featureOn the left, package by layer: packages named controller, service, repository and model each contain classes from every feature, such as ProductController and OrderController in the controller package. On the right, package by feature: packages named catalog, order and customer each contain the controller, service, repository and model for one feature, so a change to ordering stays inside the order package. Package by layer controller ProductController OrderController service ProductService OrderService repository ProductRepository OrderRepository model Product, Order, Customer Package by feature catalog ProductController, ProductService, Product... order OrderController, OrderService, Order... customer CustomerController, CustomerService... shared Money, error handling, config
By layer groups classes by technical role; by feature groups everything one business capability needs.
CriterionPackage by layerPackage by feature
Where a change happensSpread across four or more packagesUsually one package
Hiding internalsEverything must be public, since callers are in other packagesRepositories and helpers can be package-private
Finding codeEasy for small apps; packages grow huge laterPackage names describe the business
Splitting into services laterHard: features are mixed in every packageEasier: each package is a candidate module
Best forVery small applications and demosMost real applications

A practical middle ground is feature first, then layer: top-level packages per feature, and, if a feature grows large, sub-packages such as order.web and order.persistence inside it.

5. A Complete Example: A Feature-Based Shop

Here is a recommended layout for a shop with catalog, ordering and customer features:

src/main/java/com/javabytechie/shop
com/javabytechie/shop/
├── ShopApplication.java
├── catalog/
│   ├── ProductController.java        public: HTTP entry point
│   ├── ProductService.java           public: used by the order feature
│   ├── ProductRepository.java        package-private
│   ├── Product.java                  package-private entity
│   └── ProductResponse.java          public record (API contract)
├── order/
│   ├── OrderController.java
│   ├── OrderService.java
│   ├── OrderRepository.java          package-private
│   ├── Order.java
│   ├── CreateOrderRequest.java
│   └── OrderNotFoundException.java
├── customer/
│   └── ...
└── shared/
    ├── config/
    │   └── ShopProperties.java       @ConfigurationProperties record
    └── web/
        └── ApiErrorHandler.java      @RestControllerAdvice for all features

The order feature uses the catalog only through its public service, never through its repository:

ProductService.java
package com.javabytechie.shop.catalog;

import java.math.BigDecimal;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    private final ProductRepository repository;

    ProductService(ProductRepository repository) {
        this.repository = repository;
    }

    public BigDecimal currentPrice(String sku) {
        return repository.findBySku(sku)
                .map(Product::price)
                .orElseThrow(() -> new IllegalArgumentException("Unknown product " + sku));
    }
}
ProductRepository.java
package com.javabytechie.shop.catalog;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Repository;

@Repository
class ProductRepository {

    private final Map<String, Product> products = Map.of(
            "KB-100", new Product("KB-100", "Mechanical keyboard", new BigDecimal("79.99")),
            "MS-200", new Product("MS-200", "Wireless mouse", new BigDecimal("24.99")));

    Optional<Product> findBySku(String sku) {
        return Optional.ofNullable(products.get(sku));
    }
}
Product.java
package com.javabytechie.shop.catalog;

import java.math.BigDecimal;

record Product(String sku, String name, BigDecimal price) {
}
OrderService.java
package com.javabytechie.shop.order;

import com.javabytechie.shop.catalog.ProductService;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderService.class);
    private final ProductService products;

    public OrderService(ProductService products) {
        this.products = products;
    }

    public BigDecimal quote(String sku, int quantity) {
        BigDecimal total = products.currentPrice(sku).multiply(BigDecimal.valueOf(quantity));
        log.info("Quoted {} x {} = {}", quantity, sku, total);
        return total;
    }
}

Because ProductRepository and Product are package-private, the compiler stops any class in the order package from using them. Spring can still create package-private beans, so nothing else changes. The boundary is enforced for free.

Going further: The Spring Modulith project treats each direct sub-package of the root package as an application module and can verify in a test that modules only use each other's public API. It is a good next step for large monoliths.

6. Organizing src/main/resources

PathWhat goes there
application.properties or application.ymlDefault configuration for all environments (pick one format)
application-{profile}.propertiesOverrides for one profile, such as dev or prod
static/CSS, JavaScript and images served at the root URL as-is
templates/Server-rendered views such as Thymeleaf templates
db/migration/Flyway SQL migrations (V1__create_orders.sql)
messages.propertiesTranslatable texts for internationalization
banner.txtOptional custom startup banner

Never store passwords or API keys in these files: they end up inside the JAR and in version control. See managing secrets in Spring Boot.

7. Structuring Tests

Mirror the production packages in src/test/java. A test in the same package can reach package-private classes, which keeps the production code's boundaries intact.

src/test/java/com/javabytechie/shop
com/javabytechie/shop/
├── ShopApplicationTests.java         checks the whole context starts
├── catalog/
│   └── ProductServiceTest.java       unit test, no Spring context
└── order/
    ├── OrderServiceTest.java
    └── OrderControllerTest.java      @WebMvcTest slice test
OrderServiceTest.java
package com.javabytechie.shop.order;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.javabytechie.shop.catalog.ProductService;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;

class OrderServiceTest {

    @Test
    void quoteMultipliesPriceByQuantity() {
        ProductService products = mock(ProductService.class);
        when(products.currentPrice("KB-100")).thenReturn(new BigDecimal("79.99"));
        OrderService service = new OrderService(products);

        assertThat(service.quote("KB-100", 3)).isEqualByComparingTo("239.97");
    }
}

8. When to Use a Multi-Module Project

A multi-module build splits one repository into several Maven or Gradle modules, each with its own pom.xml, built together by a parent. It adds build complexity, so use it only for a clear reason:

Good reasonPoor reason
Several deployable applications share code (an API and a batch job)"It looks more professional"
You publish a client library or starter for other teamsSeparating controller, service and repository into modules
Strict compile-time boundaries between large parts are requiredA small application with one team
Multi-module layout
shop-parent/
├── pom.xml                  <packaging>pom</packaging>, lists the modules
├── shop-domain/             plain Java: domain model and rules, no Spring Boot
├── shop-api/                Spring Boot web application (has the main class)
└── shop-batch/              Spring Boot batch application (has its own main class)

Only the modules that run as applications use the Spring Boot Maven plugin to build an executable JAR. Shared modules stay ordinary JARs.

9. Common Structure Mistakes

  • Main class in a sub-package such as com.javabytechie.shop.app: classes in sibling packages are not scanned, and you get "No qualifying bean" errors or 404s for controllers that exist.
  • Huge util and common packages: they become a dumping ground. Put code next to the feature that uses it.
  • Everything public: nothing stops one feature from using another's repository. Make internals package-private.
  • Entities and DTOs in one model package: API contracts and database tables change for different reasons. Keep them apart.
  • Secrets in application.properties: they leak through Git and the JAR.
  • Committing target/ or IDE files: add them to .gitignore.

10. Best Practices

  • Place the main class in the root package and keep everything else below it.
  • Organize by feature, and add layer sub-packages only inside large features.
  • Make classes package-private by default and expose a small public API per feature.
  • Keep shared code small and limited to truly cross-cutting pieces such as error handling and configuration.
  • Mirror production packages in tests so tests can use package-private classes.
  • Use one configuration format, either properties or YAML, across the project.
  • Introduce multiple modules only for a concrete need, such as several applications sharing code.

11. Summary

A clean Spring Boot project structure follows the standard Maven or Gradle folders, keeps the @SpringBootApplication class in the root package so scanning finds every component, and organizes code by feature rather than by technical layer. Package-private classes turn each feature package into a small module with a clear public API, resources hold configuration but never secrets, and tests mirror the production packages. Start with a single module and feature packages; add sub-packages and modules only when the application grows into needing them.

12. References