Controller Service Repository

Three Layers, Three Jobs

LayerAnnotationJobKnows about
Controller@RestControllerHTTP: read the request, validate, call the service, return a response and statusDTOs, HTTP
Service@ServiceBusiness rules: stock checks, prices, transactionsEntities, repositories, other services
Repository@Repository / Spring Data interfaceLoad and save dataThe 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.