Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 37

    Service Layer Architecture

    The Orders service layer owns business rules.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Create OrderService under the application package with @Service.
    2. Constructor-inject OrderRepository and any collaborators as final fields.
    3. Implement place with validation, persistence, and a domain event/outbox publish inside @Transactional.
    4. Return an OrderView record; throw typed exceptions on conflict or missing stock.

    Informative example

    Orders place use case. Controllers call this — never the repository.

    java
    @Service
    public 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;
    }
    @Transactional
    public 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 @Transactional only 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.

    3 questions
    1BeginnerQuestionWhy put @Transactional on the service instead of the controller?+

    Answer

    The service owns the use case and may be called from jobs or messaging as well as HTTP. Controllers should stay free of persistence semantics.
    2IntermediateQuestionWhat goes wrong if self-invocation calls a @Transactional method on this?+

    Answer

    Spring AOP proxies do not intercept internal calls, so the transactional advice may never run. Extract a collaborator or use AspectJ carefully.
    3IntermediateQuestionWhy return DTOs instead of entities from OrderService?+

    Answer

    Entities carry persistence concerns and lazy associations. DTOs/records define a stable application contract and avoid accidental data leaks.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.