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

    Controllers

    An Orders controller is the HTTP edge of the service.

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

    Introduction

    An Orders controller is the HTTP edge of the service. @RestController combines @Controller with @ResponseBody, so a returned record becomes JSON through Jackson — not a view name.

    Keep controllers thin. Map the verb and path, validate the body, call OrderService, choose a status code. Pricing rules, transactions, and SQL stay out of this class.

    On Boot 3 the servlet and validation packages are jakarta.*. Constructor-inject the service; do not call new OrderService() and do not inject a repository here.

    This lesson is the shape of every later Orders endpoint. Mapping details, path variables, and CRUD semantics come next — first lock the boundary.

    Purpose of this lesson

    Write a thin Orders @RestController that delegates to a service, returns DTOs/records, and never opens persistence from the web layer.

    Understanding the topic

    HTTP translation is the controller's only job.

    • @RestController: stereotype + JSON body writing for every handler return value.
    • @RequestMapping on the class: shared prefix such as /api/orders.
    • Verb mappings: prefer @GetMapping / @PostMapping over a bare @RequestMapping that accepts every method.
    • Delegation: one constructor dependency on OrderService.
    • DTOs out: never return JPA entities from a controller.

    Step-by-step explanation

    1. Place OrderController under the OrdersApplication scan root.
    2. Annotate the class with @RestController and @RequestMapping("/api/orders").
    3. Constructor-inject OrderService into a final field.
    4. Add GET /{id} that returns an OrderView record from the service.

    Informative example

    Thin Orders controller. Expected JSON for GET /api/orders/42:

    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);
    }
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    OrderView create(@Valid @RequestBody CreateOrderRequest body) {
    return orders.place(body);
    }
    }
    record OrderView(long id, String status, int amountCents) {}
    record CreateOrderRequest(@NotBlank String sku, @Positive int qty) {}

    Output

    {"id":42,"status":"PENDING","amountCents":4999}

    Real-world use

    TechLearningPRO mobile clients hit /api/orders. If the controller embeds pricing and JDBC, every UI change risks breaking checkout rules. A thin controller lets QA mock OrderService and lets the service team change persistence without rewriting HTTP.

    Security implications

    Anything the controller exposes is reachable unless Spring Security says otherwise.

    • Do not ship sample GET-by-id routes publicly without authorization.
    • Never log full request bodies that may contain PII.
    • Reject unexpected content types explicitly on writes when the API is JSON-only.

    Best practices

    • One controller per resource family early on; split when the class stops fitting on one screen.
    • Pair mutating endpoints with @Valid once validation is on the classpath.
    • Keep path prefixes stable; version only when the contract truly breaks.

    Common mistakes

    • Injecting OrderRepository into the controller.
    • Returning entities and triggering lazy-load exceptions during JSON serialization.
    • Putting business if trees in the handler instead of the service.

    Advanced interview questions

    Interview Prep

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

    3 questions
    1BeginnerQuestionWhat does @RestController add over @Controller?+

    Answer

    It meta-annotates @ResponseBody, so return values are written to the HTTP body (typically JSON) instead of resolved as view names.
    2IntermediateQuestionWhy keep repositories out of controllers?+

    Answer

    Transactions, multi-step rules, and persistence details belong in the service. Controllers that skip the service duplicate logic and become hard to unit-test.
    3IntermediateQuestionWhat breaks if you return a JPA entity from a REST controller?+

    Answer

    Lazy associations can throw during serialization, and you leak persistence shape to clients. Map to a DTO/record at the boundary.

    Hands-on exercise

    Lab. Add OrderController as above with a fake in-memory service. Curl GET /api/orders/1. Move a pricing calculation into the controller, then move it back into the service and note which tests stay simple.

    Summary

    Orders controllers are a narrow HTTP adapter. Next lessons refine mapping, parameters, and REST semantics on top of this boundary.

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