Controllers
An Orders controller is the HTTP edge of the service.
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/@PostMappingover a bare@RequestMappingthat accepts every method. - Delegation: one constructor dependency on
OrderService. - DTOs out: never return JPA entities from a controller.
Step-by-step explanation
- Place
OrderControllerunder theOrdersApplicationscan root. - Annotate the class with
@RestControllerand@RequestMapping("/api/orders"). - Constructor-inject
OrderServiceinto afinalfield. - Add
GET /{id}that returns anOrderViewrecord from the service.
Informative example
Thin Orders controller. Expected JSON for GET /api/orders/42:
@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
@Validonce validation is on the classpath. - Keep path prefixes stable; version only when the contract truly breaks.
Common mistakes
- Injecting
OrderRepositoryinto the controller. - Returning entities and triggering lazy-load exceptions during JSON serialization.
- Putting business
iftrees in the handler instead of the service.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat does @RestController add over @Controller?+
Answer
@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
3IntermediateQuestionWhat breaks if you return a JPA entity from a REST controller?+
Answer
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.