Architecture — Layers of a Spring App
A bug report arrives: "Borrowing a book sometimes lets a member take a sixth book." Where do you look? In a well-built Spring app you know the answer before you open a file, because every kind of code has its own layer. The borrowing limit is a business rule, so it lives in exactly one place.
The rule
Requests flow down: controller, service, repository, database — and answers flow back up.
A typical Spring Boot service has three layers of your own code, each with one job:
| Layer | Job | In library-service |
|---|---|---|
| Controller (web) | Speak HTTP: read the request, return a response | BookController |
| Service (business) | Apply the rules of the domain | LoanService |
| Repository (data) | Load and save data | BookRepository |
@RestController
class BookController {
private final LoanService loans;
BookController(LoanService loans) { this.loans = loans; }
@PostMapping("/books/{id}/borrow")
Loan borrow(@PathVariable long id, @RequestParam long memberId) {
return loans.borrow(id, memberId); // no rules here, just hand over
}
}Each layer calls only the one below it. The controller never talks SQL; the repository never knows about HTTP. Spring marks the layers with matching annotations: @RestController, @Service, @Repository.
Underneath your code sits the Spring Framework itself, which is also layered. At the bottom is the core container, which creates and wires beans. On top of it sit modules such as AOP (adding behaviour around methods), data access (transactions, JDBC), and web (Spring MVC). Spring Boot wraps all of it and adds the embedded server.
The shortcut
For any piece of logic, ask "Whose job is this?"
- About HTTP (paths, status codes, JSON shape)? Controller.
- About the rules of the business (limits, prices, who may do what)? Service.
- About storing or finding data? Repository.
Is it about HTTP?
No. The limit would be the same if loans came from a mobile app or a batch job.
The trap is the "fat controller": rules written straight into controller methods. It works until a second entry point appears, and then the rule is silently skipped.
Drills
Answer fast — trust the rule.
Which layer should decide that a member may not borrow more than five books?
Which layer should choose to return HTTP status 404 when a book id is unknown?
In the layered design, what may BookController call directly?
Which part of the Spring Framework creates beans and wires them together?
Remember
- Requests flow down controller, service, repository, database; answers flow back up.
- Ask "whose job is this?": HTTP, business rule, or storage.
- Trap: fat controllers that hold business rules.
