Layered Architecture
Layered architecture is the pragmatic, Spring-shaped flavour of clean architecture: Controller → Service → Repository → DB.
Introduction
Layered architecture is the pragmatic, Spring-shaped flavour of clean architecture: Controller → Service → Repository → DB. TechLearningPRO Orders teaches and ships this shape for CRUD-heavy backends — easy to onboard, natural with Spring stereotypes, and good enough until bounded contexts demand hexagonal packaging.
Each layer owns one job: HTTP/DTOs at the web layer, transactions and orchestration in services, domain rules in entities/value objects, persistence in repositories. Skip layers only with eyes open — a controller that talks to EntityManager becomes an untestable knot.
Boot 3 / Java 21 does not change the layers; it changes packages (jakarta.*) and encourages constructor injection. Layers can later graduate to ports-and-adapters without rewriting the public API.
This lesson locks the four-layer map before Domain-Driven Design vocabulary.
Purpose of this lesson
Implement Orders with clear web, service, domain, and persistence layers and constructor injection on Boot 3.
Understanding the topic
Four standard layers — single responsibility each.
- Web/API: controllers, DTOs, validation, exception handlers.
- Service/Application: use cases,
@Transactional, orchestration. - Domain: entities, value objects, business rules.
- Persistence: Spring Data JPA repos, JDBC, native queries.
Step-by-step explanation
- Create packages:
web,service,domain,persistence. - Put REST mapping and jakarta validation on controller DTOs only.
- Keep transactions on the service; repositories stay interface-thin.
- Reject domain logic in controllers and HTTP concerns in repositories.
Informative example
Orders layered slice (Boot 3 / jakarta).
@RestController@RequestMapping("/api/orders")public class OrderController {private final OrderService orders;public OrderController(OrderService orders) { this.orders = orders; }@PostMappingResponseEntity<OrderResponse> place(@Valid @RequestBody CreateOrderRequest req) {return ResponseEntity.status(201).body(OrderResponse.from(orders.place(req)));}}@Servicepublic class OrderService {private final OrderRepository repo;public OrderService(OrderRepository repo) { this.repo = repo; }@Transactionalpublic Order place(CreateOrderRequest req) {return repo.save(Order.create(req.customerId(), req.lines()));}}public interface OrderRepository extends JpaRepository<OrderEntity, Long> {}
Real-world use
A TechLearningPRO intern once put pricing rules in the controller 'to ship faster'. Two clients needed the same rule via Kafka. Moving logic into OrderService (and later a domain method) removed duplicated discounts and made unit testing trivial.
Security implications
Layers are also choke points for validation and authz.
- Validate at the web layer with jakarta validation; re-check invariants in domain.
- Do not trust controller-only checks if messaging entry points exist.
- Never log secrets that pass through DTO fields.
Best practices
- Constructor injection; avoid field
@Autowired. - Map entities ↔ DTOs at the web or application boundary.
- Keep layers testable in isolation; graduate to hexagonal when complexity demands.
Common mistakes
- Fat controllers with transactions and persistence details.
- Anemic services that only pass DTOs to repositories with no rules.
- Leaking JPA entities as API responses and coupling clients to schema.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat belongs in the Spring service layer?+
Answer
2IntermediateQuestionHow does layered relate to clean architecture?+
Answer
3IntermediateQuestionWhy avoid returning JPA entities from controllers?+
Answer
Hands-on exercise
Lab. Split a tangled Orders class into controller, service, domain entity, and repository. Add one unit test on the service and one MockMvc test on the controller.
Summary
Layered architecture is the default Orders shape on Boot 3. Next: apply Domain-Driven Design when the business model gets complex.