Spring Boot Architecture
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.
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:
| Level | What it contains | Examples |
|---|---|---|
| Your application | Controllers, services, repositories, configuration | OrderController, OrderService |
| Starters | Dependency bundles, one per capability | spring-boot-starter-webmvc, spring-boot-starter-data-jpa |
| Spring Boot modules | The core (SpringApplication, configuration binding), technology modules with their auto-configuration, Actuator, DevTools, test support and the JAR launcher | spring-boot, spring-boot-webmvc, spring-boot-actuator, spring-boot-loader |
| Spring Framework | IoC container, AOP, MVC, transactions, data access | spring-context, spring-webmvc, spring-tx |
| Libraries and server | Embedded server, JSON, persistence and logging libraries | Tomcat, Jackson, Hibernate, Logback |
| JVM | Java 17 or later | Java 25 |
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
@Entityclasses.
Keeping DTOs separate from entities means you can change the database without breaking API clients, and the other way around.
| Layer | Annotation | Allowed to call | Must not |
|---|---|---|---|
| Presentation | @RestController | Services | Contain business rules or call repositories |
| Business | @Service | Repositories, other services, clients | Use HTTP types such as ResponseEntity |
| Data access | @Repository | The database | Call 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:
- Embedded server: Tomcat accepts the connection and assigns a worker thread (or a virtual thread if enabled).
- Filters: servlet filters run in order. Spring Security is a filter, so authentication happens here, before any controller.
- DispatcherServlet: Spring MVC's front controller. It asks the handler mappings which
@GetMappingmethod matches, then runs anyHandlerInterceptorobjects. - Argument resolution: path variables, query parameters and the JSON body are converted into method parameters. A JSON body is read by an
HttpMessageConverter(Jackson). - Controller, service, repository: your code runs, layer by layer.
- 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
package com.javabytechie.shop.order;
import java.math.BigDecimal;
public record Order(long id, String customerEmail, String sku, int quantity, BigDecimal total) {
}
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
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
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));
}
}
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
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
curl -i -X POST http://localhost:8080/api/orders \
-H "Content-Type: application/json" \
-d '{"customerEmail":"asha@example.com","sku":"KB-100","quantity":2}'
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:
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());
}
}
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"}
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:
| Concern | Where Spring handles it |
|---|---|
| Authentication and authorization | Spring Security filter chain, before the DispatcherServlet |
| Request logging and correlation IDs | A servlet filter or a HandlerInterceptor |
| Transactions | @Transactional proxy around service methods |
| Caching | @Cacheable proxy around service methods |
| Metrics and tracing | Micrometer 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
ResponseEntitycannot 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
@RestControllerAdviceandProblemDetail. - 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
Spring Boot Architecture Interview Questions and Answers
Common interview questions on Spring Boot Architecture, from basic to scenario-based, with short answers you can explain in your own words.
Q. Explain the architecture of a typical Spring Boot application.
Answer: At the framework level, the application runs on Spring Boot modules (starters, auto-configuration, embedded server, Actuator) on top of the Spring Framework and the JVM. Inside, code is usually split into a presentation layer of @RestController classes, a business layer of @Service classes that own rules and transactions, and a data access layer of @Repository classes. DTOs carry data across the HTTP boundary and entities or domain objects carry it inside.
Q. What does the DispatcherServlet do in a Spring Boot web application?
Answer: It is Spring MVC's front controller: every request handled by Spring MVC goes through it. It finds the matching handler through handler mappings, runs interceptors, resolves method arguments, calls the controller, converts the return value with an HttpMessageConverter and routes exceptions to exception resolvers such as your @RestControllerAdvice. Spring Boot registers it automatically and maps it to /.
Q. Why should a controller not call a repository directly?
Answer: Business rules and transaction boundaries belong in the service layer. A controller that calls a repository skips them, so the same rule ends up duplicated in several controllers or forgotten. It also ties the web layer to the database model, which makes both harder to change and test. Even a simple pass-through service gives you one place to add rules later.
Q. How does a Spring MVC controller's return value become a JSON response?
Answer: For @RestController methods, the DispatcherServlet passes the return value to a return value handler, which picks an HttpMessageConverter based on the value's type and the request's Accept header. For JSON the Jackson converter serializes the object and writes it to the response body with the application/json content type. ResponseEntity return values also set the status and headers.
Q. Should the service layer return ResponseEntity?
Answer: No. ResponseEntity is an HTTP type, and a service should be usable from a message listener, a scheduled job or a test without HTTP. The service returns domain objects and throws business exceptions; the controller builds the response, and a controller advice maps exceptions to status codes.
Q. A controller method has grown to 150 lines with pricing, stock checks and email sending. How would you refactor it?
Answer: Move each business step into the service layer: a pricing component, an inventory service and a notification service, coordinated by an order service method that is the single @Transactional boundary. Send the email after the commit, for example from a transactional event listener, so a mail failure cannot roll back the order. The controller is left with validating input, calling one service method and mapping the result to a DTO.