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.