Learn / Frameworks / Spring Boot / Domain Events and Messaging

Spring Boot · Lesson 13 of 15

Domain Events and Messaging

Application events in-process and a first look at a message broker.

  • Advanced
  • 16 min read
  • 3 objectives

Before this lessonLesson 12: Uploads and Scheduling

What you will learn

  • Publish an event
  • Listen @TransactionalEventListener
  • Sketch a queue

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Decouple "order placed" from "send email" with events. Start in-process; move to a broker when another service must consume the same fact.

Application events

public record OrderPlaced(long orderId, String email) {}

@Service
public class CheckoutService {
    private final ApplicationEventPublisher events;
    @Transactional
    public void checkout(Cart cart) {
        Order order = orders.save(...);
        events.publishEvent(new OrderPlaced(order.getId(), cart.getEmail()));
    }
}

@Component
public class MailListener {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void on(OrderPlaced event) {
        mail.sendReceipt(event.email(), event.orderId());
    }
}

AFTER_COMMIT avoids sending mail for a rolled-back order. Listeners in the same JVM still fail silently if the process dies; a queue (RabbitMQ, SQS, Kafka) is the next step.

When to use a broker

  • Another service needs the event.
  • Work must retry independently of the web node.
  • You need a durable audit of what happened.
Up next · Lesson 14Tests with TestcontainersSlice tests, MockMvc and a real Postgres in Docker for integration tests.