Service Layer Architecture
The Orders service layer owns business rules.
Introduction
The Orders service layer owns business rules. Controllers translate HTTP; repositories talk to the database; the service decides whether a checkout is legal, starts the transaction, and orchestrates inventory, persistence, and side effects.
On Boot 3 / Java 21, mark the class with @Service, constructor-inject collaborators into final fields, and put @Transactional on use-case methods (or the class) — never on the controller.
A healthy Orders service accepts commands/DTOs, returns views/DTOs, and throws domain exceptions such as OrderNotFoundException or ConflictException. It never reads HttpServletRequest and never returns JPA entities to the web tier.
This lesson locks the boundary so security, JWT, and REST hardening later attach to a clear application core — not to a fat controller.
Purpose of this lesson
Design an Orders @Service that owns transactions and business rules, orchestrates repositories/clients, and stays free of HTTP concerns.
Understanding the topic
Thin controllers + fat services + dumb repositories scale.
- Use-case methods:
place,cancel,get— one public method per intent. - @Transactional: boundaries live here so multi-step writes commit or roll back together.
- Orchestration: repositories, inventory clients, outbox publishers — coordinated in one place.
- DTOs in/out: never expose entities across the HTTP boundary.
- Domain exceptions: map to problem details later; do not leak SQL exceptions upward.
Step-by-step explanation
- Create
OrderServiceunder the application package with@Service. - Constructor-inject
OrderRepositoryand any collaborators asfinalfields. - Implement
placewith validation, persistence, and a domain event/outbox publish inside@Transactional. - Return an
OrderViewrecord; throw typed exceptions on conflict or missing stock.
Informative example
Orders place use case. Controllers call this — never the repository.
@Servicepublic class OrderService {private final OrderRepository orders;private final InventoryClient inventory;private final OutboxPublisher outbox;public OrderService(OrderRepository orders, InventoryClient inventory, OutboxPublisher outbox) {this.orders = orders;this.inventory = inventory;this.outbox = outbox;}@Transactionalpublic OrderView place(CreateOrderRequest cmd) {if (!inventory.reserve(cmd.sku(), cmd.qty())) {throw new ConflictException("SKU out of stock");}OrderEntity saved = orders.save(OrderEntity.from(cmd));outbox.publish(new OrderPlaced(saved.getId(), saved.getCustomerId()));return OrderView.from(saved);}@Transactional(readOnly = true)public OrderView get(long id) {return orders.findById(id).map(OrderView::from).orElseThrow(() -> new OrderNotFoundException(id));}}
Real-world use
TechLearningPRO checkout must reserve inventory and write the order atomically. If the controller calls two repositories without a shared transaction, a crash between steps leaves stock reserved and no order — or the reverse. Putting both steps in OrderService.place with @Transactional keeps the ledger consistent under load.
Security implications
Authorization checks often belong next to the use case, not only on the URL.
- Do not trust a client-supplied
customerId— bind to the authenticated principal in the service. - Log business decisions with order ids, never raw credentials.
- Keep inventory and payment secrets out of service method signatures and logs.
Best practices
- One service per aggregate early; split when the class no longer fits one screen.
- Prefer constructor injection; avoid field injection in new code.
- Keep side effects (email, messaging) behind outbox or after-commit hooks when consistency matters.
Common mistakes
- Injecting the repository into the controller and skipping the service.
- Putting
@Transactionalonly on private methods (proxy never applies). - Returning entities and triggering lazy-load failures during JSON serialization.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy put @Transactional on the service instead of the controller?+
Answer
2IntermediateQuestionWhat goes wrong if self-invocation calls a @Transactional method on this?+
Answer
3IntermediateQuestionWhy return DTOs instead of entities from OrderService?+
Answer
Hands-on exercise
Lab. Implement OrderService.place with an in-memory repository. Add a deliberate failure after save and confirm the transaction rolls back. Then call the same method from a thin controller.
Summary
The Orders service layer is the application core. With that boundary fixed, Spring Security can protect who may call each use case.