What belongs in each layer
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite creates products from a web request, from a nightly supplier import and from tests. If the price and SKU rules sit in the web code, the other two callers skip them. Layers give each job one home.
Controller: HTTP in and out only
A controller is the layer that speaks HTTP: it reads the request (path, query parameters, JSON body), calls one service method and turns the result into a status code, headers and a JSON body.
Here is ShopLite's ProductController: every method reads HTTP input, makes one service call and returns the result.
Example 1 · src/main/java/com/shoplite/product/ProductController.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import java.math.BigDecimal;import java.net.URI;
import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.server.ResponseStatusException;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.shoplite.common.PageResponse;
/** HTTP in and out for products. Every decision about products is made by ProductService. */@RestController@RequestMapping("/api/v1/products")class ProductController {
private final ProductService service;
ProductController(ProductService service) { this.service = service; }
@GetMapping PageResponse<ProductResponse> list(@RequestParam(required = false) String q, @RequestParam(required = false) Long categoryId, @RequestParam(required = false) BigDecimal minPrice, @RequestParam(required = false) BigDecimal maxPrice, @RequestParam(defaultValue = "false") boolean inStock, @RequestParam(defaultValue = "false") boolean includeInactive, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) { // Temporary checks: the Validation module replaces them with @Min, @Max and field errors. if (page < 0 || size < 1 || size > 100) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "page must be >= 0 and size 1-100"); } if (minPrice != null && maxPrice != null && minPrice.compareTo(maxPrice) > 0) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "minPrice must not be above maxPrice"); } ProductFilter filter = new ProductFilter(q, categoryId, minPrice, maxPrice, inStock, includeInactive); return service.search(filter, page, size); }
@GetMapping("/{id}") ProductResponse get(@PathVariable Long id) { return service.get(id); }
@PostMapping ResponseEntity<ProductResponse> create(@RequestBody CreateProductRequest request) { ProductResponse created = service.create(request); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(created.id()).toUri(); return ResponseEntity.created(location).body(created); }
@PutMapping("/{id}") ProductResponse replace(@PathVariable Long id, @RequestBody UpdateProductRequest request) { return service.replace(id, request); }
@DeleteMapping("/{id}") ResponseEntity<Void> delete(@PathVariable Long id) { service.delete(id); return ResponseEntity.noContent().build(); }}$ curl http://localhost:8080/api/v1/products/1
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}What this code does
- Each method reads HTTP input (
@PathVariable,@RequestParam,@RequestBody), calls exactly oneProductServicemethod and returns its result. There is noifabout prices, SKUs or categories. - The only checks here are about the request itself: the
pageandsizelimits andminPriceabovemaxPrice. They are marked temporary, because the Validation module replaces them with annotations. ResponseEntity.created(location)andnoContent()are HTTP decisions, so they stay in the controller. The output shows one call toGET /api/v1/products/1.
Rules written in a controller work only for web requests. A nightly import, a test or a second endpoint would have to copy them, and the copies drift apart.
A quick test for any line in a controller: would it still make sense if the request came from a command-line tool instead of a browser? If yes, it is a rule, and it belongs in the service.
public keyword: only Spring calls them. The Package by layer vs package by feature lesson explains why.Service: business rules, coordination and later transactions
A service is the layer that decides: it holds the business rules, calls one or more repositories in the right order and returns the result. It knows nothing about HTTP.
Here is ProductService: it checks the category and the SKU, and only then asks the repository to save.
Example 2 · src/main/java/com/shoplite/product/ProductService.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.shoplite.category.CategoryService;import com.shoplite.common.BusinessRuleException;import com.shoplite.common.ConflictException;import com.shoplite.common.NotFoundException;import com.shoplite.common.PageResponse;
/** Product rules. Takes and returns DTOs; the Product entity stays inside this class and the repository. */@Servicepublic class ProductService {
private final ProductRepository repository; private final CategoryService categoryService;
ProductService(ProductRepository repository, CategoryService categoryService) { this.repository = repository; this.categoryService = categoryService; }
public PageResponse<ProductResponse> search(ProductFilter filter, int page, int size) { List<Product> products = repository.findPage(filter, page * size, size); long total = repository.count(filter); return PageResponse.of(toResponses(products), page, size, total); }
public ProductResponse get(Long id) { Product product = load(id); return ProductMapper.toResponse(product, categoryName(product.getCategoryId())); }
public ProductResponse create(CreateProductRequest request) { String categoryName = categoryName(request.categoryId()); checkSkuIsFree(null, request.sku()); Product saved = repository.save(ProductMapper.toNewProduct(request)); return ProductMapper.toResponse(saved, categoryName); }
public ProductResponse replace(Long id, UpdateProductRequest request) { Product product = load(id); String categoryName = categoryName(request.categoryId()); checkSkuIsFree(id, request.sku()); ProductMapper.copyInto(request, product); return ProductMapper.toResponse(repository.save(product), categoryName); }
public void delete(Long id) { if (!repository.existsById(id)) { throw new NotFoundException("Product " + id + " was not found."); } repository.deleteById(id); }
private Product load(Long id) { return repository.findById(id) .orElseThrow(() -> new NotFoundException("Product " + id + " was not found.")); }
private String categoryName(Long categoryId) { return categoryService.findName(categoryId) .orElseThrow(() -> new BusinessRuleException("Category " + categoryId + " does not exist.")); }
private void checkSkuIsFree(Long id, String sku) { repository.findBySku(sku) .filter(other -> !other.getId().equals(id)) .ifPresent(other -> { throw new ConflictException("A product with SKU " + sku + " already exists."); }); }
private List<ProductResponse> toResponses(List<Product> products) { Set<Long> categoryIds = products.stream().map(Product::getCategoryId).collect(Collectors.toSet()); Map<Long, String> names = categoryService.findNames(categoryIds); return products.stream() .map(p -> ProductMapper.toResponse(p, names.get(p.getCategoryId()))) .toList(); }}$ curl -i -X POST http://localhost:8080/api/v1/products -H 'Content-Type: application/json' -d '{"sku":"MOB-RN13","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 409
Content-Type: application/json
{"timestamp":"2026-10-16T05:19:38.169Z","status":409,"error":"Conflict","path":"/api/v1/products"}What this code does
createchecks the category first (422 if it is missing), then the SKU (409 if it is taken), and only then saves. The output is the 409 a client gets for an SKU that already exists.- Failed rules throw
BusinessRuleException,ConflictExceptionorNotFoundExceptionfromcom.shoplite.common. The service never mentions a status code; for now@ResponseStatuson each exception class does that. ProductMapperconverts between the storedProductand the request and response records; the next lesson builds it. The class ispublicso other features can use it, but its constructor is package-private because only Spring calls it.
When a rule fails, the service throws an exception that names the problem in business words, such as ConflictException; something else turns it into a status code.
Later the service is also where a transaction starts: a group of database changes that succeed or fail together, such as saving an order and reducing stock. The last module of this section adds that with @Transactional.
@ResponseStatus on each ShopLite exception class tells Spring which status to send. The Exception Handling module replaces it with one global handler that returns the API contract's error format.Repository: storing and loading data, nothing else
A repository is the layer that stores and loads data. Its method names read like questions and commands about rows (findById, findBySku, save, deleteById), and it makes no decisions.
Here is ProductRepository: an interface with storage methods only.
Example 3 · src/main/java/com/shoplite/product/ProductRepository.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import java.util.List;import java.util.Optional;
/** Stores and loads products. No business rules, no HTTP. */interface ProductRepository {
Optional<Product> findById(Long id);
Optional<Product> findBySku(String sku);
List<Product> findAll();
/** One page of matching products, by id. */ List<Product> findPage(ProductFilter filter, int offset, int limit);
long count(ProductFilter filter);
boolean existsById(Long id);
Product save(Product product);
void deleteById(Long id);}$ grep -rn "implements ProductRepository" src/main/java
src/main/java/com/shoplite/product/InMemoryProductRepository.java:19:class InMemoryProductRepository implements ProductRepository {What this code does
- Every method is about storage: find, count, save, delete. None of them mentions HTTP, and none of them decides anything about prices or SKUs.
Optional<Product>fromfindByIdsays "there may be no such row". The service decides that a missing product meansNotFoundException.- The
grepshows the one class that implements the interface today. The An in-memory repository lesson builds it, and the last module adds a MySQL version with the same methods.
A repository never judges whether a price is sensible or a SKU is allowed; it only answers "is there a product with this SKU?". That keeps storage swappable: ShopLite starts with an in-memory repository and moves to MySQL in the last module of this section, keeping the same methods.
Every repository is an interface with one implementing class, so the service never knows where the data actually lives.
Following one request through all three layers
Layered architecture splits an application into layers with one job each, such as controller, service and repository. A request travels down through the layers and the answer comes back up.
Here is POST /api/v1/products followed through all three layers in plain Java, one printed line per step.
Example 4 · One request through three layers, in plain Java
import java.math.BigDecimal;import java.util.HashMap;import java.util.Map;import java.util.Set;
record CreateProductRequest(String sku, String name, long categoryId, BigDecimal price) {}
record ProductResponse(long id, String sku, String name, BigDecimal price) {}
record Product(long id, String sku, String name, long categoryId, BigDecimal price) {}
class RuleBrokenException extends RuntimeException { RuleBrokenException(String message) { super(message); }}
class AlreadyExistsException extends RuntimeException { AlreadyExistsException(String message) { super(message); }}
// Repository: stores and loads, nothing elseclass ProductRepository { private final Map<String, Product> rowsBySku = new HashMap<>(); private long nextId = 16;
boolean existsBySku(String sku) { System.out.println(" [repository] look up SKU " + sku); return rowsBySku.containsKey(sku); }
Product save(Product product) { Product row = new Product(nextId++, product.sku(), product.name(), product.categoryId(), product.price()); rowsBySku.put(row.sku(), row); System.out.println(" [repository] saved " + row.sku() + " as id " + row.id()); return row; }}
// Service: the rulesclass ProductService { private static final Set<Long> CATEGORY_IDS = Set.of(1L, 2L, 3L, 4L, 5L, 6L, 7L); private final ProductRepository repository;
ProductService(ProductRepository repository) { this.repository = repository; }
ProductResponse create(CreateProductRequest request) { System.out.println(" [service] check the rules for " + request.sku()); if (!CATEGORY_IDS.contains(request.categoryId())) { throw new RuleBrokenException("Category " + request.categoryId() + " does not exist."); } if (repository.existsBySku(request.sku())) { throw new AlreadyExistsException("A product with SKU " + request.sku() + " already exists."); } Product saved = repository.save( new Product(0, request.sku(), request.name(), request.categoryId(), request.price())); return new ProductResponse(saved.id(), saved.sku(), saved.name(), saved.price()); }}
// Controller: HTTP in, HTTP outclass ProductController { private final ProductService service;
ProductController(ProductService service) { this.service = service; }
String post(CreateProductRequest body) { System.out.println("[controller] POST /api/v1/products sku=" + body.sku()); try { ProductResponse created = service.create(body); return "201 Created, Location: /api/v1/products/" + created.id(); } catch (RuleBrokenException e) { return "422 " + e.getMessage(); } catch (AlreadyExistsException e) { return "409 " + e.getMessage(); } }}
public class RequestFlowDemo { public static void main(String[] args) { ProductController controller = new ProductController(new ProductService(new ProductRepository())); BigDecimal price = new BigDecimal("999.00");
System.out.println(controller.post(new CreateProductRequest("ACC-KB100", "Wireless Keyboard", 4, price))); System.out.println(); System.out.println(controller.post(new CreateProductRequest("ACC-KB100", "Wireless Keyboard", 4, price))); System.out.println(); System.out.println(controller.post(new CreateProductRequest("ACC-KB200", "Gaming Keyboard", 42, price))); }}[controller] POST /api/v1/products sku=ACC-KB100
[service] check the rules for ACC-KB100
[repository] look up SKU ACC-KB100
[repository] saved ACC-KB100 as id 16
201 Created, Location: /api/v1/products/16
[controller] POST /api/v1/products sku=ACC-KB100
[service] check the rules for ACC-KB100
[repository] look up SKU ACC-KB100
409 A product with SKU ACC-KB100 already exists.
[controller] POST /api/v1/products sku=ACC-KB200
[service] check the rules for ACC-KB200
422 Category 42 does not exist.What this code does
- The indentation shows the depth: controller, then service, then repository. The first request reaches the repository twice: once to look up the SKU and once to save.
- The second request stops in the service after the SKU lookup, so nothing is saved. The third stops even earlier, at the category rule, and never touches the repository.
- This plain
ProductControllercatches the exceptions and picks the status itself. In Spring, that translation happens in one place for the whole app.
Example 5 · The same trip through the real ShopLite API
Runs in: the shoplite-api Spring Boot project
curl -i -X POST http://localhost:8080/api/v1/products -H 'Content-Type: application/json' -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'curl http://localhost:8080/api/v1/products/16curl -i -X POST http://localhost:8080/api/v1/products -H 'Content-Type: application/json' -d '{"sku":"ACC-KB200","name":"Zebronics Gaming Keyboard","categoryId":42,"price":1499.00}'$ curl -i -X POST http://localhost:8080/api/v1/products -H 'Content-Type: application/json' -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json
{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}
$ curl http://localhost:8080/api/v1/products/16
{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}
$ curl -i -X POST http://localhost:8080/api/v1/products -H 'Content-Type: application/json' -d '{"sku":"ACC-KB200","name":"Zebronics Gaming Keyboard","categoryId":42,"price":1499.00}'
HTTP/1.1 422
Content-Type: application/json
{"timestamp":"2026-10-16T05:19:07.245Z","status":422,"error":"Unprocessable Content","path":"/api/v1/products"}What this code does
- The first call passes all three layers and returns 201 with the new id 16.
categoryNameis there because the service asked the category feature for it. - The third call stops in the service with 422. Its body is Spring Boot's default error JSON; the Exception Handling module turns it into the contract's ProblemDetail format.
- Date and length headers are left out, and your timestamps will differ. Run the commands in Git Bash on Windows or in Terminal on macOS.
In the real app Spring calls the controller and turns exceptions into status codes. The controller reads the JSON into a CreateProductRequest, the service checks the rules and asks the repository to save, and the controller turns the saved product into 201 Created with a Location header.
When a rule fails, the trip stops inside the service: the repository is never asked to save, and the exception travels back up to become a 409 or a 422.
Order of execution
The trip of one POST
Tap the steps in the order they happen.
Dependencies point one way: controller to service to repository
A dependency is another object a class needs to do its job; in Spring it arrives through the constructor. In a layered app the controller depends on the service, and the service depends on the repository.
Here is one PriceService called by two callers: a web controller and a nightly import with no HTTP at all.
Example 6 · One service, two callers
import java.math.BigDecimal;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
class PriceRuleException extends RuntimeException { PriceRuleException(String message) { super(message); }}
class PriceRepository { private final Map<String, BigDecimal> priceBySku = new LinkedHashMap<>();
void save(String sku, BigDecimal price) { priceBySku.put(sku, price); }
BigDecimal find(String sku) { return priceBySku.get(sku); }
Map<String, BigDecimal> all() { return priceBySku; }}
// Service: one rule, written once - a new price may not be more than 50% above the old oneclass PriceService { private static final BigDecimal MAX_RISE = new BigDecimal("1.5"); private final PriceRepository repository;
PriceService(PriceRepository repository) { this.repository = repository; }
void changePrice(String sku, BigDecimal newPrice) { BigDecimal old = repository.find(sku); if (old != null && newPrice.compareTo(old.multiply(MAX_RISE)) > 0) { throw new PriceRuleException(sku + ": " + old + " -> " + newPrice + " is a rise of more than 50%"); } repository.save(sku, newPrice); }}
// Caller 1: the web controller (one price per HTTP request)class PriceController { private final PriceService service;
PriceController(PriceService service) { this.service = service; }
String put(String sku, String body) { try { service.changePrice(sku, new BigDecimal(body)); return "200 OK"; } catch (PriceRuleException e) { return "422 " + e.getMessage(); } }}
// Caller 2: a nightly job that reads the supplier's CSV price list - no HTTP at allclass SupplierPriceImport { private final PriceService service;
SupplierPriceImport(PriceService service) { this.service = service; }
void run(List<String> csvLines) { for (String line : csvLines) { String[] parts = line.split(","); try { service.changePrice(parts[0], new BigDecimal(parts[1])); System.out.println("import: " + parts[0] + " updated"); } catch (PriceRuleException e) { System.out.println("import: skipped, " + e.getMessage()); } } }}
public class TwoCallersDemo { public static void main(String[] args) { PriceRepository repository = new PriceRepository(); repository.save("BK-CLEAN", new BigDecimal("499.00")); repository.save("ACC-AD141", new BigDecimal("1299.00")); PriceService service = new PriceService(repository);
PriceController controller = new PriceController(service); System.out.println("web: " + controller.put("BK-CLEAN", "549.00")); System.out.println("web: " + controller.put("BK-CLEAN", "999.00"));
new SupplierPriceImport(service).run(List.of("ACC-AD141,1199.00", "BK-CLEAN,2499.00")); System.out.println("prices now: " + repository.all()); }}web: 200 OK
web: 422 BK-CLEAN: 549.00 -> 999.00 is a rise of more than 50%
import: ACC-AD141 updated
import: skipped, BK-CLEAN: 549.00 -> 2499.00 is a rise of more than 50%
prices now: {BK-CLEAN=549.00, ACC-AD141=1199.00}What this code does
PriceServiceholds the 50% rule once. The web controller and the nightly import both call it, and both are refused for the same price jump.SupplierPriceImporthas no HTTP at all, yet the rule still runs. That works only because the arrows point from the callers to the service, never back.- The import carries on after a refused row, so
ACC-AD141is updated whileBK-CLEANkeeps its web price of 549.00.
The arrows point one way only, which makes a service reusable: it never knows who is calling. A service that needed a controller would work only inside a web request, and if two classes needed each other, Spring would refuse to start. Shared helpers, such as a rupee formatter, sit below the services: anyone may use them, and they use nobody.
Which arrows are allowed:
- Controller → service: allowed.
- Service → repository, and service → another feature's service: allowed.
- Repository → service, or service → controller: not allowed.
- Controller → repository: skips the rules. The Common layering mistakes lesson shows the damage.
Next step
Check your understanding
12 quick questions