00:00

Spring Boot Architecture

Last updated:

Spring Boot architecture can mean two things, and you need both. The first is how Spring Boot itself is built: a set of modules on top of the Spring Framework that supply starters, auto-configuration and an embedded server. The second is how you structure your own application: a presentation layer, a business layer and a data access layer that pass a request from the web server to the database and back. Understanding both makes it clear where each class belongs and what Spring does between your classes.

This tutorial explains the framework layers, the application layers and the full path of an HTTP request. It then builds a small layered order API, shows how errors travel back through the layers, and lists the common design mistakes.

1. What Is Spring Boot Architecture?

An architecture is the set of big parts of a system and the rules for how they talk to each other. For a Spring Boot application there are two views:

  • The framework view: your code runs on Spring Boot, which runs on the Spring Framework, which runs on the JVM. Each level adds features to the one below.
  • The application view: your code is split into layers. Each layer has one responsibility and talks only to the layer directly below it.
Analogy: A restaurant has a building with a kitchen, electricity and water (the framework view), and a way of working: waiters take orders, cooks prepare food, the store room keeps ingredients (the application view). A waiter never goes into the store room. Spring Boot provides the building; you organize the staff.

2. How Spring Boot Itself Is Built

Spring Boot is not a separate framework. It is a set of modules that configure and run the Spring Framework for you:

LevelWhat it containsExamples
Your applicationControllers, services, repositories, configurationOrderController, OrderService
StartersDependency bundles, one per capabilityspring-boot-starter-webmvc, spring-boot-starter-data-jpa
Spring Boot modulesThe core (SpringApplication, configuration binding), technology modules with their auto-configuration, Actuator, DevTools, test support and the JAR launcherspring-boot, spring-boot-webmvc, spring-boot-actuator, spring-boot-loader
Spring FrameworkIoC container, AOP, MVC, transactions, data accessspring-context, spring-webmvc, spring-tx
Libraries and serverEmbedded server, JSON, persistence and logging librariesTomcat, Jackson, Hibernate, Logback
JVMJava 17 or laterJava 25
Version note: Up to Spring Boot 3.x, almost all auto-configuration lived in one large spring-boot-autoconfigure JAR. Spring Boot 4 split it into smaller technology modules, such as spring-boot-webmvc and spring-boot-jdbc, so an application only carries the auto-configuration it uses. Starters pull in the right modules for you.

When the application starts, these levels meet: SpringApplication creates the Spring container, auto-configuration adds infrastructure beans for the libraries that starters put on the classpath, and the embedded server begins to accept requests. The startup process tutorial covers this in detail.

3. The Layered Architecture of a Spring Boot Application

Most Spring Boot services use three layers, plus the model classes that move between them.

3.1 Presentation Layer

Classes annotated with @RestController. They receive HTTP requests, validate the input, call a service and turn the result into an HTTP response. They contain no business rules and do not talk to the database.

3.2 Business (Service) Layer

Classes annotated with @Service. They hold the business rules ("an order needs at least one item", "stock cannot go below zero"), coordinate repositories and other services, and define transaction boundaries with @Transactional. They know nothing about HTTP.

3.3 Data Access (Persistence) Layer

Classes or interfaces annotated with @Repository, often Spring Data repositories. They read and write data and translate database errors into Spring's DataAccessException hierarchy. They contain no business rules.

3.4 Models That Move Between Layers

  • Request and response DTOs (data transfer objects): records that define the API's JSON. They belong to the presentation layer.
  • Domain objects or entities: the business data the service works with. With JPA these are @Entity classes.

Keeping DTOs separate from entities means you can change the database without breaking API clients, and the other way around.

LayerAnnotationAllowed to callMust not
Presentation@RestControllerServicesContain business rules or call repositories
Business@ServiceRepositories, other services, clientsUse HTTP types such as ResponseEntity
Data access@RepositoryThe databaseCall services or make business decisions

4. How a Request Flows Through Spring Boot

Here is what happens when a client sends GET /api/orders/1001:

Request flow through a Spring Boot applicationAn HTTP request arrives at the embedded Tomcat server. Servlet filters such as security and logging run first. The DispatcherServlet asks the handler mapping which controller method matches the URL, runs interceptors, and calls the controller. The controller calls the service, which applies business rules and calls the repository, which queries the database. The result returns to the controller as a domain object, the controller maps it to a response DTO, and an HTTP message converter writes it as JSON back through the filters to the client. Client GET /api/orders/1001 Embedded Tomcat thread per request Filters security, logging DispatcherServlet handler mapping, interceptors Controller @RestController Service @Service business rules Repository @Repository Database Response: DTO mapped in controller, written as JSON by a message converter The response travels back through DispatcherServlet, filters and Tomcat to the client
A request passes through the server, filters and DispatcherServlet before it reaches your controller; the response returns the same way as JSON.
  1. Embedded server: Tomcat accepts the connection and assigns a worker thread (or a virtual thread if enabled).
  2. Filters: servlet filters run in order. Spring Security is a filter, so authentication happens here, before any controller.
  3. DispatcherServlet: Spring MVC's front controller. It asks the handler mappings which @GetMapping method matches, then runs any HandlerInterceptor objects.
  4. Argument resolution: path variables, query parameters and the JSON body are converted into method parameters. A JSON body is read by an HttpMessageConverter (Jackson).
  5. Controller, service, repository: your code runs, layer by layer.
  6. Response: the return value is written to the response body by a message converter, and the response passes back through the filters to the client.

5. A Complete Example: A Layered Order API

The example keeps orders in memory, so you can run it with only spring-boot-starter-webmvc and spring-boot-starter-validation. Swapping the repository for Spring Data JPA later does not change the controller or the service, which is the point of layering.

5.1 Domain and DTOs

Order.java
package com.javabytechie.shop.order;

import java.math.BigDecimal;

public record Order(long id, String customerEmail, String sku, int quantity, BigDecimal total) {
}
OrderDtos.java
package com.javabytechie.shop.order;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;

public final class OrderDtos {

    private OrderDtos() {
    }

    public record CreateOrderRequest(@Email @NotBlank String customerEmail,
                                     @NotBlank String sku,
                                     @Positive int quantity) {
    }

    public record OrderResponse(long id, String sku, int quantity, BigDecimal total) {

        static OrderResponse from(Order order) {
            return new OrderResponse(order.id(), order.sku(), order.quantity(), order.total());
        }
    }
}

5.2 Data Access Layer

OrderRepository.java
package com.javabytechie.shop.order;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Repository;

@Repository
public class OrderRepository {

    private final Map<Long, Order> orders = new ConcurrentHashMap<>();
    private final AtomicLong ids = new AtomicLong(1000);

    public Order save(String customerEmail, String sku, int quantity, BigDecimal total) {
        Order order = new Order(ids.incrementAndGet(), customerEmail, sku, quantity, total);
        orders.put(order.id(), order);
        return order;
    }

    public Optional<Order> findById(long id) {
        return Optional.ofNullable(orders.get(id));
    }
}

5.3 Business Layer

OrderService.java
package com.javabytechie.shop.order;

import com.javabytechie.shop.order.OrderDtos.CreateOrderRequest;
import java.math.BigDecimal;
import java.util.Map;
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 static final Map<String, BigDecimal> PRICES = Map.of(
            "KB-100", new BigDecimal("79.99"),
            "MS-200", new BigDecimal("24.99"));

    private final OrderRepository repository;

    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }

    public Order place(CreateOrderRequest request) {
        BigDecimal price = PRICES.get(request.sku());
        if (price == null) {
            throw new UnknownProductException(request.sku());
        }
        BigDecimal total = price.multiply(BigDecimal.valueOf(request.quantity()));
        Order order = repository.save(request.customerEmail(), request.sku(), request.quantity(), total);
        log.info("Placed order {} for {} x {}", order.id(), request.quantity(), request.sku());
        return order;
    }

    public Order find(long id) {
        return repository.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
    }
}
OrderExceptions.java
package com.javabytechie.shop.order;

class OrderNotFoundException extends RuntimeException {
    OrderNotFoundException(long id) {
        super("Order " + id + " was not found");
    }
}

class UnknownProductException extends RuntimeException {
    UnknownProductException(String sku) {
        super("Product " + sku + " does not exist");
    }
}

5.4 Presentation Layer

OrderController.java
package com.javabytechie.shop.order;

import com.javabytechie.shop.order.OrderDtos.CreateOrderRequest;
import com.javabytechie.shop.order.OrderDtos.OrderResponse;
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService service;

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

    @PostMapping
    public ResponseEntity<OrderResponse> place(@Valid @RequestBody CreateOrderRequest request) {
        Order order = service.place(request);
        return ResponseEntity.created(URI.create("/api/orders/" + order.id()))
                .body(OrderResponse.from(order));
    }

    @GetMapping("/{id}")
    public OrderResponse find(@PathVariable long id) {
        return OrderResponse.from(service.find(id));
    }
}

5.5 Try It

Terminal
curl -i -X POST http://localhost:8080/api/orders \
  -H "Content-Type: application/json" \
  -d '{"customerEmail":"asha@example.com","sku":"KB-100","quantity":2}'
Response
HTTP/1.1 201
Location: /api/orders/1001
Content-Type: application/json

{"id":1001,"sku":"KB-100","quantity":2,"total":159.98}

Notice the direction of the dependencies: the controller knows the service, the service knows the repository, and nothing points upwards. The customer email is stored but not returned, because the response DTO decides what the API exposes.

6. How Errors Travel Back Through the Layers

The service throws business exceptions; it does not choose HTTP status codes. A @RestControllerAdvice in the presentation layer translates them into responses using ProblemDetail, the standard RFC 9457 error format:

OrderErrorHandler.java
package com.javabytechie.shop.order;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
class OrderErrorHandler {

    @ExceptionHandler(OrderNotFoundException.class)
    ProblemDetail notFound(OrderNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(UnknownProductException.class)
    ProblemDetail unknownProduct(UnknownProductException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, ex.getMessage());
    }
}
Response for GET /api/orders/42
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"about:blank","title":"Not Found","status":404,"detail":"Order 42 was not found","instance":"/api/orders/42"}
Version note: Spring Framework 7 names status 422 HttpStatus.UNPROCESSABLE_CONTENT, the name used by RFC 9110. The older constant UNPROCESSABLE_ENTITY is deprecated. For all the options, see exception handling in Spring Boot.

7. Cross-Cutting Concerns

Some concerns apply to every layer: security, logging, transactions, caching and metrics. Spring keeps them out of your business code with proxies, filters and interceptors:

ConcernWhere Spring handles it
Authentication and authorizationSpring Security filter chain, before the DispatcherServlet
Request logging and correlation IDsA servlet filter or a HandlerInterceptor
Transactions@Transactional proxy around service methods
Caching@Cacheable proxy around service methods
Metrics and tracingMicrometer observations, enabled by Actuator

The proxy mechanism behind @Transactional and @Cacheable is explained in AOP in Spring Boot.

8. Common Architecture Mistakes

  • Business rules in controllers. The rules cannot be reused by a scheduler or a message listener. Move them to the service.
  • Controllers calling repositories. This skips transaction boundaries and validation in the service.
  • Returning JPA entities as JSON. Lazy relationships fail outside a transaction and internal fields leak to clients. Return DTOs.
  • HTTP types in services. A service that returns ResponseEntity cannot be reused outside the web layer. Throw exceptions and let the advice map them.
  • One giant service. A class with dozens of methods hides several responsibilities. Split by business capability.

9. Best Practices

  • Keep dependencies pointing downwards: controller to service to repository, never back up.
  • Put transaction boundaries on service methods, where one business operation starts and ends.
  • Use records for DTOs and map them at the edge, in the controller.
  • Translate exceptions in one place with @RestControllerAdvice and ProblemDetail.
  • Inject dependencies through constructors so each layer's needs are explicit and easy to test.
  • Group code by feature as the application grows; see Spring Boot project structure.

10. Summary

Spring Boot architecture has two sides. Underneath, your code runs on starters and Spring Boot modules that configure the Spring Framework, which runs on the JVM with an embedded server. Inside your application, a presentation layer handles HTTP, a business layer applies the rules and owns transactions, and a data access layer talks to the database. A request passes through Tomcat, the filters and the DispatcherServlet before it reaches your controller, and errors come back as ProblemDetail responses through a controller advice. Keep each layer to its job and the dependencies pointing downwards, and the application stays easy to test and change.

11. References