Careeroza
Controller Service Repository
Three Layers, Three Jobs
| Layer | Annotation | Job | Knows about |
|---|---|---|---|
| Controller | @RestController | HTTP: read the request, validate, call the service, return a response and status | DTOs, HTTP |
| Service | @Service | Business rules: stock checks, prices, transactions | Entities, repositories, other services |
| Repository | @Repository / Spring Data interface | Load and save data | The database |
HTTP request
|
v
+------------------+ DTOs +------------------+ entities +---------------------+
| ProductController| ------------> | ProductService | -------------> | ProductRepository | --> DB
| (web layer) | <------------ | (business layer) | <------------- | (data layer) |
+------------------+ +------------------+ +---------------------+Why Bother?
- Testability: the service can be unit-tested without a web server or database.
- Reuse: the same
OrderService.placeOrder()is called from the REST API, a Kafka listener and a scheduled job. - Change: switch from an in-memory store to MySQL by changing only the repository.
- Readability: every class has one clear job.
Note: Dependencies only point downwards: controller → service → repository. A repository never calls a service, and a service never returns ResponseEntity.