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

    Spring Boot Architecture

    A maintainable Spring Boot service is layered: the web layer speaks HTTP, the service layer owns business rules and transactions, the persistence layer talks to the database, an…

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

    Introduction

    A maintainable Spring Boot service is layered: the web layer speaks HTTP, the service layer owns business rules and transactions, the persistence layer talks to the database, and configuration wires infrastructure beans.

    DispatcherServlet is the front controller for servlet MVC. It routes to a @RestController method, which should validate input, call a service, and return a DTO or record — not open a DataSource.

    When Orders grows, the temptation is to put pricing, inventory, and persistence in the controller. That creates untestable HTTP-bound logic and forces every change through a web test. Layers exist so you can unit-test OrderService.place with fakes.

    This lesson is about boundaries, not folders. You may package by layer early and by feature later; the call direction stays the same: controller → service → repository.

    Purpose of this lesson

    Draw the Orders request path through Controller → Service → Repository and state what each layer may and may not depend on.

    Understanding the topic

    Dependency rules beat package names.

    • Controller: HTTP mapping, status codes, DTO/record mapping. No SQL. No multi-step business workflows.
    • Service: use cases, invariants, @Transactional boundaries. Depends on ports/repositories, not on HttpServletRequest.
    • Repository: persistence only. Spring Data interfaces or JdbcClient. No authorization decisions.
    • Domain: entities/records that model Orders. Keep HTTP annotations off domain types.
    • Config: @Bean for RestClient, Clock, data sources — not business rules.

    Step-by-step explanation

    1. Sketch GET /api/orders/{id} from client to database on paper.
    2. Name the types: OrderController, OrderService, OrderRepository, OrderView.
    3. Forbid repository injection into the controller in code review.
    4. When a feature needs two repositories, orchestrate in the service — not in the controller.

    Syntax reference

    Happy-path request flow:

    bash
    HTTP GET /api/orders/42
    │
    ▼
    DispatcherServlet
    │
    ▼
    OrderController.getOne(id) // map HTTP ↔ OrderView
    │
    ▼
    OrderService.get(id) // rules, @Transactional if writes
    │
    ▼
    OrderRepository // JPA / JDBC
    │
    ▼
    PostgreSQL

    Informative example

    Thin controller, injectable service. The controller does not know how pricing works.

    java
    @RestController
    @RequestMapping("/api/orders")
    public class OrderController {
    private final OrderService orders;
    public OrderController(OrderService orders) { this.orders = orders; }
    @GetMapping("/{id}")
    OrderView getOne(@PathVariable long id) {
    return orders.get(id);
    }
    }

    Real-world use

    Payment platforms model a transfer as controller (authz + DTO) → service (idempotency, ledger postings, fraud checks) → repositories (accounts, ledger lines). TechLearningPRO Orders follows the same seam so checkout rules can be tested without MockMvc for every assertion.

    Best practices

    • DTOs/records at the HTTP boundary; entities inside the service/persistence edge.
    • One public use-case method on the service per business action when possible.
    • Keep controllers short enough to read without scrolling.

    Common mistakes

    • Injecting OrderRepository into OrderController.
    • Returning JPA entities from controllers (lazy loads, accidental over-exposure).
    • Putting @Transactional only on the controller — web concerns and persistence lifecycle get tangled.

    Advanced interview questions

    Interview Prep

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

    3 questions
    1BeginnerQuestionWhy shouldn't a controller call a repository directly?+

    Answer

    Business rules, transactions, and multi-repository orchestration belong in the service. Controllers that skip the service become untestable outside the web layer and duplicate logic across endpoints.
    2IntermediateQuestionWhat is the role of DispatcherServlet?+

    Answer

    It is Spring MVC's front controller: it dispatches HTTP requests to handler methods and applies message conversion, validation, and exception resolvers.
    3AdvancedQuestionWhen is package-by-feature better than package-by-layer?+

    Answer

    When the codebase is large enough that feature teams own vertical slices. Early Orders can stay layer packages; the dependency rule stays identical either way.

    Hands-on exercise

    Lab. List three Orders features (get, place, cancel). For each, write which layer owns the work and which types are forbidden to import in the controller.

    Summary

    Orders stays healthy when each layer has one job. The next lessons install the toolchain and scaffold the project that will hold these layers.

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