Spring Boot Project Structure
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/resourcesandsrc/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.
2. The Standard Folder Layout
A project generated by Spring Initializr looks like this:
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 file | Purpose | Ends up in the JAR? |
|---|---|---|
src/main/java | Production Java code | Yes, compiled to BOOT-INF/classes |
src/main/resources | Configuration, templates, static files, SQL migrations | Yes, copied to BOOT-INF/classes |
src/test/java | Unit and integration tests | No |
src/test/resources | Test-only configuration and data | No |
target/ or build/ | Build output | It 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.
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)
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.
| Criterion | Package by layer | Package by feature |
|---|---|---|
| Where a change happens | Spread across four or more packages | Usually one package |
| Hiding internals | Everything must be public, since callers are in other packages | Repositories and helpers can be package-private |
| Finding code | Easy for small apps; packages grow huge later | Package names describe the business |
| Splitting into services later | Hard: features are mixed in every package | Easier: each package is a candidate module |
| Best for | Very small applications and demos | Most 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:
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:
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));
}
}
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));
}
}
package com.javabytechie.shop.catalog;
import java.math.BigDecimal;
record Product(String sku, String name, BigDecimal price) {
}
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.
6. Organizing src/main/resources
| Path | What goes there |
|---|---|
application.properties or application.yml | Default configuration for all environments (pick one format) |
application-{profile}.properties | Overrides 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.properties | Translatable texts for internationalization |
banner.txt | Optional 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.
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
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 reason | Poor 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 teams | Separating controller, service and repository into modules |
| Strict compile-time boundaries between large parts are required | A small application with one team |
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
utilandcommonpackages: 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
modelpackage: 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
Spring Boot Project Structure Interview Questions and Answers
Common interview questions on Spring Boot Project Structure, from basic to scenario-based, with short answers you can explain in your own words.
Q. Why should the @SpringBootApplication class be in the root package?
Answer: Component scanning and auto-configuration packages both start from the main class's package and include its sub-packages. With the main class in the root package, every controller, service, repository and JPA entity below it is found. Classes in sibling or parent packages are not scanned unless you add scanBasePackages, @EntityScan and similar settings by hand.
Q. Package by layer or package by feature: which do you prefer, and why?
Answer: Package by feature for most real applications. A change usually touches one feature, so its classes should sit together; internals such as repositories can be package-private, which the compiler then protects; and features can later be extracted into modules or services. Package by layer is acceptable for very small applications, but its packages grow large and force everything to be public.
Q. What is the difference between the static and templates folders in src/main/resources?
Answer: Files in static/ are served unchanged at the root URL, so static/css/site.css becomes /css/site.css. Files in templates/ are not served directly; a template engine such as Thymeleaf renders them with data when a controller returns a view name. A pure REST API usually needs neither.
Q. When would you split a Spring Boot application into several Maven modules?
Answer: When there is a concrete need: several deployable applications share domain code, a client library or starter is published for other teams, or large parts need boundaries enforced at compile time. Splitting controllers, services and repositories into separate modules usually adds build complexity without benefit; feature packages with package-private classes give most of the separation for free.
Q. Can Spring create beans from package-private classes and constructors?
Answer: Yes. Component scanning finds package-private classes annotated with @Component or its specializations, and Spring can call package-private constructors. This lets a feature package hide its repositories and helpers while still letting Spring wire them. The limit is other packages: they can only inject the feature's public types.
Q. After a refactoring, the main class moved to com.javabytechie.shop.app and every endpoint now returns 404. What happened?
Answer: Scanning now starts at com.javabytechie.shop.app, so controllers in sibling packages such as com.javabytechie.shop.order are no longer registered, and Spring MVC finds no handler for the URLs. Move the main class back to com.javabytechie.shop. Setting scanBasePackages would also work, but repositories and entities may then need extra configuration, so fixing the location is the cleaner solution.