Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 91

    Layered Architecture

    Layered architecture is the pragmatic, Spring-shaped flavour of clean architecture: Controller → Service → Repository → DB.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Layered architecture is the pragmatic, Spring-shaped flavour of clean architecture: Controller → Service → Repository → DB. TechLearningPRO Orders teaches and ships this shape for CRUD-heavy backends — easy to onboard, natural with Spring stereotypes, and good enough until bounded contexts demand hexagonal packaging.

    Each layer owns one job: HTTP/DTOs at the web layer, transactions and orchestration in services, domain rules in entities/value objects, persistence in repositories. Skip layers only with eyes open — a controller that talks to EntityManager becomes an untestable knot.

    Boot 3 / Java 21 does not change the layers; it changes packages (jakarta.*) and encourages constructor injection. Layers can later graduate to ports-and-adapters without rewriting the public API.

    This lesson locks the four-layer map before Domain-Driven Design vocabulary.

    Purpose of this lesson

    Implement Orders with clear web, service, domain, and persistence layers and constructor injection on Boot 3.

    Understanding the topic

    Four standard layers — single responsibility each.

    • Web/API: controllers, DTOs, validation, exception handlers.
    • Service/Application: use cases, @Transactional, orchestration.
    • Domain: entities, value objects, business rules.
    • Persistence: Spring Data JPA repos, JDBC, native queries.

    Step-by-step explanation

    1. Create packages: web, service, domain, persistence.
    2. Put REST mapping and jakarta validation on controller DTOs only.
    3. Keep transactions on the service; repositories stay interface-thin.
    4. Reject domain logic in controllers and HTTP concerns in repositories.

    Informative example

    Orders layered slice (Boot 3 / jakarta).

    java
    @RestController
    @RequestMapping("/api/orders")
    public class OrderController {
    private final OrderService orders;
    public OrderController(OrderService orders) { this.orders = orders; }
    @PostMapping
    ResponseEntity<OrderResponse> place(@Valid @RequestBody CreateOrderRequest req) {
    return ResponseEntity.status(201).body(OrderResponse.from(orders.place(req)));
    }
    }
    @Service
    public class OrderService {
    private final OrderRepository repo;
    public OrderService(OrderRepository repo) { this.repo = repo; }
    @Transactional
    public Order place(CreateOrderRequest req) {
    return repo.save(Order.create(req.customerId(), req.lines()));
    }
    }
    public interface OrderRepository extends JpaRepository<OrderEntity, Long> {}

    Real-world use

    A TechLearningPRO intern once put pricing rules in the controller 'to ship faster'. Two clients needed the same rule via Kafka. Moving logic into OrderService (and later a domain method) removed duplicated discounts and made unit testing trivial.

    Security implications

    Layers are also choke points for validation and authz.

    • Validate at the web layer with jakarta validation; re-check invariants in domain.
    • Do not trust controller-only checks if messaging entry points exist.
    • Never log secrets that pass through DTO fields.

    Best practices

    • Constructor injection; avoid field @Autowired.
    • Map entities ↔ DTOs at the web or application boundary.
    • Keep layers testable in isolation; graduate to hexagonal when complexity demands.

    Common mistakes

    • Fat controllers with transactions and persistence details.
    • Anemic services that only pass DTOs to repositories with no rules.
    • Leaking JPA entities as API responses and coupling clients to schema.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat belongs in the Spring service layer?+

    Answer

    Use-case orchestration and transaction boundaries — not raw HTTP mapping or SQL strings.
    2IntermediateQuestionHow does layered relate to clean architecture?+

    Answer

    It is the pragmatic Spring mapping of the same idea; hexagonal packaging is a later refinement.
    3IntermediateQuestionWhy avoid returning JPA entities from controllers?+

    Answer

    It couples API clients to persistence shape and risks lazy-load and over-exposure bugs.

    Hands-on exercise

    Lab. Split a tangled Orders class into controller, service, domain entity, and repository. Add one unit test on the service and one MockMvc test on the controller.

    Summary

    Layered architecture is the default Orders shape on Boot 3. Next: apply Domain-Driven Design when the business model gets complex.

    Ready to mark this lesson complete?Track your journey across the entire course.