Layered Architecture Pattern
Learn how to organize a backend application into clear responsibilities. Understand Controller, Service, Repository, Model, DTO, Mapper, Security and supporting components through one practical Book Management API.
1. What is Layered Architecture?
A Layered Architecture organizes an application into layers, where each layer has a defined responsibility. Instead of putting HTTP handling, business rules, and database queries into one large class, we separate them into components that work together.
Imagine building a Book Management API. A user sends a request to get a book. The controller receives the request, the service decides what should happen, and the repository fetches the book from the database.
Why use it?
Separation of concerns
HTTP handling, business rules, and data access do not become mixed together.
Maintainability
Changes are easier to locate because responsibilities are organized.
Testability
You can test business logic without requiring a real HTTP request or database.
Reuse
Multiple endpoints can call the same service operations when appropriate.
2. Understand the architecture flow
For a typical read request, the call path looks like this:
3. Practical example: Book Management API
Suppose a client requests GET /api/books/10. The API should return the book’s ID, title, and author. If the book does not exist, it should return a suitable not-found response.
Step 1 — Model: represent the book
The model represents the stored entity. In a JPA application, an entity is commonly mapped to a database table.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
protected Book() {}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public void setTitle(String title) { this.title = title; }
public void setAuthor(String author) { this.author = author; }
}Step 2 — Repository: retrieve the book
The repository handles persistence operations. Spring Data JPA can generate the implementation for common CRUD operations.
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository
extends JpaRepository<Book, Long> {
}Step 3 — DTO: define the API response
A Data Transfer Object controls what information is exposed to the API client. It avoids returning the persistence entity directly when a separate response shape is appropriate.
public record BookResponse(
Long id,
String title,
String author
) {}Step 4 — Mapper: convert the entity to a DTO
The mapper keeps conversion code out of the controller and service.
public final class BookMapper {
private BookMapper() {}
public static BookResponse toResponse(Book book) {
return new BookResponse(
book.getId(),
book.getTitle(),
book.getAuthor()
);
}
}Step 5 — Exception: represent a missing book
A custom exception gives the application a clear way to represent a domain error.
public class BookNotFoundException
extends RuntimeException {
public BookNotFoundException(Long id) {
super("Book not found with id: " + id);
}
}Step 6 — Service: apply the business operation
The service coordinates the use case. It asks the repository for the book and throws a meaningful exception if no record exists.
import org.springframework.stereotype.Service;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
public Book getBook(Long id) {
return repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
}
}Step 7 — Controller: expose the HTTP endpoint
The controller handles the HTTP request and response. It delegates the work to the service instead of querying the database itself.
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public ResponseEntity<BookResponse> getBook(
@PathVariable Long id) {
Book book = service.getBook(id);
return ResponseEntity.ok(BookMapper.toResponse(book));
}
}What response does the client receive?
For an existing book, the API could return HTTP 200 OK:
{
"id": 10,
"title": "Clean Code",
"author": "Robert C. Martin"
}For a missing book, the custom exception needs a handler to translate it into HTTP 404 Not Found. The next section explains the supporting components.
4. Components explained with examples
Expand each component to understand its responsibility and how it fits into the Book API. The first four are the core parts of a common layered application; the rest support cross-cutting concerns, data conversion, configuration, or asynchronous workflows.
Responsibility: Handles HTTP requests, reads path/query parameters, validates incoming request shapes where appropriate, calls the service, and returns an HTTP response.
Book example: GET /api/books/10 enters BookController, which calls bookService.getBook(10).
Should not: contain complex business rules or direct database query logic.
Responsibility: Implements use cases, enforces business rules, and coordinates repositories or other services.
Book example: checks whether a book exists and applies rules before returning it.
Should not: become a place for all unrelated application logic. Keep operations focused and cohesive.
Responsibility: Provides an interface for data persistence, such as CRUD operations and queries.
Book example: findById(10) fetches the record from the database using Spring Data JPA.
JPA/Hibernate is one common Java persistence approach; other applications may use JDBC, MyBatis, or another data-access tool.
Responsibility: Represents domain data. A JPA entity maps to a database table, while domain models may also represent business concepts that are not database entities.
Book example: Book contains the book ID, title, and author.
Model, entity, and DTO are related concepts but are not interchangeable terms.
Responsibility: Represents errors and translates them into meaningful responses or recovery behavior.
Book example: BookNotFoundException is thrown if the requested ID does not exist. A Spring @RestControllerAdvice can map it to HTTP 404.
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ResponseEntity<String> handleNotFound(
BookNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}This simple example returns a string. A production API often returns a structured error DTO with a message, timestamp, and error code.
Responsibility: Holds small, reusable helper functions that do not naturally belong to a particular domain service.
Examples: date formatting, string normalization, or a generic parsing helper.
Guideline: avoid turning Util into a dumping ground. Business rules should generally live in the relevant domain or service component.
Responsibility: Defines the data shape sent into or out of an API or between boundaries.
Book example: BookResponse exposes only the ID, title, and author. A CreateBookRequest could accept the title and author for a create operation.
DTOs can help avoid exposing internal fields, database implementation details, or sensitive attributes.
Responsibility: Declares application setup and framework beans that are not simply business logic.
Examples: Spring @Configuration classes for bean definitions, JSON serialization settings, or application-level wiring.
Environment-specific values such as database URLs and credentials should normally be externalized rather than hard-coded.
Responsibility: Names stable values that are reused and meaningful within a defined scope.
Example: A pagination default or a stable application-level limit. Use enums for a fixed set of related choices when appropriate.
Avoid creating a giant global constants class for unrelated values. Configuration that varies by environment belongs in configuration properties.
Responsibility: Converts between types, such as entities and DTOs.
Book example: BookMapper.toResponse(book) creates a BookResponse from a Book.
For larger projects, mapping may be handled by dedicated mapper classes or a library such as MapStruct.
Responsibility: Encapsulates reusable criteria or rules for selecting records. The exact meaning depends on the project and framework.
Book example: a Spring Data JPA Specification<Book> could filter books by author, title, or publication status and combine criteria dynamically.
Specifications are particularly useful for complex search screens; they are not mandatory for every application.
Responsibility: Publishes messages or events for other components or services to process asynchronously.
Book example: after a book is added, a producer may publish a BookCreated event to a message broker.
In a reliable production system, consider transaction boundaries, delivery guarantees, retries, and the transactional outbox pattern where appropriate.
Responsibility: Receives and processes messages produced by another component or service.
Book example: a consumer could receive BookCreated and update a search index or send a notification.
Consumers should account for duplicate deliveries, failures, retries, and idempotency. A consumer is not required in a simple synchronous CRUD API.
Responsibility: Protects application resources through authentication, authorization, and other security controls.
Book example: only an authenticated user with the required permission can create or delete a book.
With Spring Security, request filters commonly run before controller execution. Method-level authorization may also protect service operations. Validate access on the server; hiding a button in the frontend is not authorization.
5. Example project structure
One possible Spring Boot structure for the Book Management API is:
com.example.books
├── controller
│ └── BookController.java
├── service
│ └── BookService.java
├── repository
│ └── BookRepository.java
├── model
│ └── Book.java
├── dto
│ └── BookResponse.java
├── mapper
│ └── BookMapper.java
├── exception
│ ├── BookNotFoundException.java
│ └── GlobalExceptionHandler.java
├── config
│ └── AppConfig.java
├── specification
│ └── BookSpecification.java
├── security
│ └── SecurityConfig.java
├── util
│ └── DateUtils.java
└── resources
└── application.propertiesThis is an illustrative structure, not a mandatory folder layout. Add constants or messaging producer/consumer packages only when the application needs them. A small application does not need a class or folder for every possible component.
6. Best practices and common mistakes
| Good practice | Common mistake |
|---|---|
| Keep controllers focused on HTTP and delegation. | Putting business rules and database calls directly in controllers. |
| Keep business rules in cohesive services or domain objects. | Making one service class responsible for every feature. |
| Use repositories for persistence operations. | Making repositories decide API responses or business workflows. |
| Use DTOs when an API contract should differ from an entity. | Exposing every database field automatically. |
| Handle exceptions centrally where appropriate. | Returning HTTP 200 for failures or leaking internal stack traces. |
| Keep dependencies pointing through clear abstractions. | Letting every component call every other component without boundaries. |
| Add messaging, specifications and utilities when they solve a real need. | Creating extra layers and classes without a clear responsibility. |
What are the limitations?
- Applications can become over-layered if every simple operation requires many unnecessary classes.
- Business logic can become scattered if responsibilities are poorly defined.
- Strict layer boundaries need deliberate design; a folder structure alone does not enforce them.
- Layered architecture is not the same as microservices. A single application can use layered architecture internally.
7. Test your understanding
In the Book API example, which component should fetch the book record from the database?