Skip to main content
PreparationZone Logo
PrepZone

Controller → Service → Repository

The three layers every Boot REST app uses and what belongs in each one.

Pass checkpoint below

Why this matters

  • Layered architecture is the default pattern for Spring Boot REST services — violating it creates untestable controllers and duplicated business logic.
  • Clear boundaries let you swap JPA for JDBC or add caching without touching controllers.
  • Code reviews and interviews expect you to articulate what belongs in each layer.

Three layers

L1 · Fresher

Controller handles HTTP, service holds business rules, repository talks to the database. BookStore never lets controllers call JDBC directly.

Dependency direction

L2 · Intermediate

Dependencies point inward: controller → service → repository. DTOs cross the web boundary; entities stay inside the persistence layer.

Thin controllers

L3 · Advanced

Controllers validate input, map DTOs, and delegate — no transaction or JPQL in @RestController methods.

When layers blur

L4 · Expert

Shared kernel modules or hexagonal ports can replace strict layering in large systems — still keep HTTP concerns out of repositories.

The three layers

ControllerHTTP in/out — @RestController
ServiceBusiness rules — @Service
RepositoryDatabase — @Repository
DatabasePostgreSQL / H2
Each layer has one job. Dependencies point inward — controllers never touch the database directly.

Responsibilities in BookStore

  • Controller — Parse HTTP, validate input, call service, map to response DTO, set status codes. No business rules.
  • Service — Business logic, transaction boundaries, orchestration across repositories. No HTTP awareness.
  • Repository — Data access only. Queries, saves, deletes. No business validation.

Controller layer

Java
// learn:fragment
@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/{id}")
    public BookResponse getBook(@PathVariable Long id) {
        return BookResponse.from(bookService.findById(id));
    }
}

The controller knows about HTTP (@GetMapping, status codes) and DTOs. It delegates all decisions to BookService.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 7 sections

  • Service layer
  • Repository layer
  • Dependency direction
  • DTOs at layer boundaries
  • Package structure
  • Cross-cutting concerns
  • When to add more layers

Test yourself

Answer these before moving on — recall is what makes it stick.