Skip to content
javahacks.dev
Architecture

Layered Architecture in Spring Boot and Its Real Costs

Controller, service and repository layers in Spring Boot: what they give a simple application, where they leak and what to change when the domain grows.

6 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Spring Security and Gradle logos.

Controller, service, repository. Almost every Spring Boot tutorial and most production services are laid out this way, and for a good reason: it is the shortest path from zero to a working endpoint. It is also the structure behind a lot of the sprawl teams complain about two years in, with fat services, entities in JSON and a package tree nobody can navigate. Neither verdict is quite right. Layering is a fine default that has specific costs, and the costs are predictable enough to see coming and cheap enough to avoid if you know where they sit. This post shows the structure, where it works well, and the five costs with code, then what to change as the domain grows. Examples use Spring Boot 4 and Java 25.

The structure

Three layers, each allowed to call the one below it and nothing else.

LayerClass typeResponsibilityMay depend on
Web@RestControllerHTTP in and out, validation, status codesService
Service@ServiceUse cases, transactionsRepository
Persistence@Repository or Spring Data interfaceReading and writing rowsThe database

A complete slice for one feature looks like this:

src/main/java/dev/javahacks/shop/OrderController.javajava
@RestController
@RequestMapping("/orders")
class OrderController {

    private final OrderService service;

    OrderController(OrderService service) {
        this.service = service;
    }

    @PostMapping
    ResponseEntity<OrderResponse> place(@RequestBody @Valid PlaceOrder request) {
        return ResponseEntity.status(201).body(service.place(request));
    }
}
src/main/java/dev/javahacks/shop/OrderService.javajava
@Service
class OrderService {

    private final OrderRepository orders;

    OrderService(OrderRepository orders) {
        this.orders = orders;
    }

    @Transactional
    OrderResponse place(PlaceOrder request) {
        Order order = new Order(request.customerId(), request.sku(), request.quantity());
        return OrderResponse.from(orders.save(order));
    }
}
src/main/java/dev/javahacks/shop/OrderRepository.javajava
interface OrderRepository extends JpaRepository<Order, Long> { }

The rule is that dependencies point downward and the controller never touches a repository. The Spring team's own advice on structuring your code assumes this shape without requiring it.

Where it works

For an application whose logic is mostly "validate, save, read back", the layers cost almost nothing and give you three real things: a transaction boundary in one obvious place (the service), a unit that is easy to test with a mocked repository, and a layout every new hire recognizes on day one. A CRUD service with a dozen tables and little business logic is a good fit, and adding more structure to it is a cost with no return. If that is your service, stop reading and ship it. The step-by-step build of such a service is in building a Spring MVC REST API.

The trouble starts when the domain has rules, because the layers give those rules no home.

Cost 1: the anemic domain

The entity holds fields and getters. Every rule lands in the service, which grows a method per use case, each one reading and writing the entity's state from outside:

java
@Transactional
public void ship(long orderId) {
    Order order = orders.findById(orderId).orElseThrow();
    if (order.getStatus() != Status.PAID) {
        throw new IllegalStateException("cannot ship an unpaid order");
    }
    order.setStatus(Status.SHIPPED);
}

The rule "only a paid order ships" now lives in this method. A second service that also changes the status, say a bulk import or a scheduled job, has to remember it, and eventually one does not. Martin Fowler named this the anemic domain model. The remedy is to move behavior onto the object that owns the data:

java
public void ship() {
    if (status != Status.PAID) {
        throw new IllegalStateException("cannot ship an unpaid order");
    }
    status = Status.SHIPPED;
}

Now order.ship() is the only way to ship, and the rule exists once. The patterns for doing this consistently are in tactical DDD patterns in Java.

Cost 2: pass-through services

When the controller calls the service and the service calls the repository with the same arguments, the middle layer exists only because the diagram says so:

java
@Service
class CustomerService {
    Customer find(long id) { return customers.findById(id).orElseThrow(); }
    Customer save(Customer c) { return customers.save(c); }
    void delete(long id) { customers.deleteById(id); }
}

Each method adds a stack frame, a class to open and a test that checks a mock was called. It buys nothing, and it hides where the transaction really starts. The test for a pass-through is to delete the layer for that feature and see whether anything is lost. If nothing is, let the controller use the repository for plain reads, and keep services for use cases that coordinate several things. Consistency is not a virtue strong enough to justify a hundred empty methods.

Cost 3: entities in the API

The shortest path from a controller to a response is to return the entity. The layering diagram does not forbid it, because the entity is just "the model". The consequences are the ones the API-design post lists: renaming a column breaks clients, Jackson recurses through bidirectional links as in infinite recursion with bidirectional entities, and a lazy association read after the transaction ends throws the exception described in LazyInitializationException.

Put a record at each boundary:

java
record OrderResponse(long id, String status, long totalCents) {
    static OrderResponse from(Order o) {
        return new OrderResponse(o.getId(), o.getStatus().name(), o.totalCents());
    }
}

The mapping code is tedious, and it is also the cheapest insurance in the whole architecture.

Cost 4: the database is the center

In a strict layered design every dependency points down, so the domain depends on persistence: the service imports JpaRepository, and the entity carries JPA annotations. The business rules cannot be exercised without the persistence framework on the classpath, and swapping or even faking the store means touching the core. For most services that is acceptable. For a service whose rules are the product, the inversion is worth the extra interface: the domain declares what it needs, and the infrastructure implements it. The argument and the code are in dependency inversion beyond the slogan, with a full structure in hexagonal architecture with Spring Boot. Be honest about the price, which is more interfaces and mapping, and about how often you will really swap a database (rarely).

Cost 5: packaging by layer

The most visible symptom is the package tree:

Text
dev.javahacks.shop
  controller/   OrderController, CustomerController, ProductController, ...
  service/      OrderService, CustomerService, ProductService, ...
  repository/   OrderRepository, CustomerRepository, ProductRepository, ...
  model/        Order, Customer, Product, ...

Everything is public, because the layers need to see each other across packages. A change to orders touches four packages, and nothing marks the boundary between orders and customers, so they drift together. Package by feature instead, and make most classes package-private:

Text
dev.javahacks.shop
  orders/      OrderController, OrderService, OrderRepository, Order
  customers/   CustomerController, CustomerService, CustomerRepository, Customer
  catalog/     ProductController, ProductService, ProductRepository, Product

Now OrderRepository can be package-private, and the compiler enforces that nobody outside orders reaches into it. The layers still exist inside each package. When you want that boundary checked, Spring Modulith verifies it in a test, and clean architecture, and where it gets heavy covers the next step up.

What to change as the domain grows

Do it in the order of cheapest first, and only when the pain shows.

  1. Stop returning entities. Add response records. Do it now.
  2. Package by feature. A move-and-rename refactor that the IDE does for you.
  3. Make repositories and services package-private where they are internal to a feature.
  4. Move rules onto entities when the same condition appears in two services.
  5. Introduce a repository interface owned by the domain only where you feel the persistence framework in your tests.
  6. Add an architecture test, so the structure you chose stays chosen.

Where this does not apply

If the application is a thin layer over a database, with no rules, even three layers can be more than you need; a controller over repositories is honest. If it is the other extreme, a core domain with complex rules and several integrations, plain layering will fray, and you need the ports and domain model from the posts linked above from the start. The mistake is not choosing layers. It is choosing them by habit, and keeping them after they stopped helping.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.