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

    Service Layer Architecture

    The service layer owns business rules.

    Course progress0%
    Focus
    4 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    The service layer owns business rules. It's the only layer allowed to start transactions, orchestrate multiple repositories and call external systems.

    Understanding the topic

    Anatomy of a healthy service:

    • Pure business logic — zero HTTP concerns.
    • Owns transaction boundaries (@Transactional at this layer).
    • Talks to repositories and other services, returns DTOs or domain objects.
    • Throws domain exceptions (NotFoundException, ConflictException).

    Informative example

    ts
    @Service
    @Transactional
    @RequiredArgsConstructor
    public class OrderService {
    private final OrderRepository orders;
    private final InventoryClient inventory;
    private final OutboxPublisher outbox;
    public OrderDto place(NewOrder cmd) {
    if (!inventory.reserve(cmd.items())) {
    throw new ConflictException("Items out of stock");
    }
    var order = orders.save(Order.from(cmd));
    outbox.publish(new OrderPlaced(order.id(), order.userId()));
    return OrderDto.from(order);
    }
    }

    Best practices

    • One service per aggregate — don't build a 5 000-line BusinessService.
    • Pass DTOs/commands in, return DTOs out. Never expose entities.
    • Cross-service writes → outbox pattern, not chained HTTP calls.
    Ready to mark this lesson complete?Track your journey across the entire course.