BBackend CourseLeroy Labs
0/0
Search the course

Domain events & @TransactionalEventListener

Decoupling with ApplicationEventPublisher, synchronous vs after-commit listeners, transaction phases, why you notify only after commit, and Spring Modulith's @ApplicationModuleListener.

● advancedReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

A domain event is a fact in past tense: JournalPosted, ApproversAssigned, CompanyCreated. The code that publishes it doesn’t know or care who listens, which keeps modules decoupled.

public record JournalPosted(UUID companyId, UUID entryId, String number, LocalDate date) {}

@Service
class DefaultPostingEngine implements PostingEngine {
    private final ApplicationEventPublisher events;

    @Transactional
    public JournalEntry post(UUID entryId) {
        JournalEntry e = /* validate, number, mark posted ... */;
        events.publishEvent(new JournalPosted(e.companyId(), e.id(), e.number(), e.date()));
        return e;
    }
}

Listener types and phases

@EventListener                     // runs IMMEDIATELY, same thread, same transaction
void onSync(JournalPosted e) { /* ... */ }   // exception here rolls back the poster!

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)   // default phase
void afterCommit(JournalPosted e) { /* ... */ }  // runs only if the poster committed

// also: BEFORE_COMMIT, AFTER_ROLLBACK, AFTER_COMPLETION

Why AFTER_COMMIT matters

❌ @EventListener sends "Your booking is approved" email
   -> later in the same transaction the commit fails (constraint violation)
   -> user got an email for something that never happened

✅ @TransactionalEventListener(AFTER_COMMIT)
   -> email only after the DB truly has the approval

The flip side is that if the app crashes between commit and the listener, the event is lost. The next lesson (the outbox pattern) closes that gap.

In your projects

Report-Manager-2module/report/application/PendingBacklogNotifier.java · approvalassignment/domain/ApproversAssignedEvent

@TransactionalEventListener(phase = AFTER_COMMIT) notifies approvers only once the assignment is committed. The audit pipeline (AuditListener, AuditPublisher) also runs on events.

IR3D (Kontentt)campaign/application/CampaignAssetWithdrawal.java:32 · TransactionalRabbitPublisher

An AFTER_COMMIT listener for campaign withdrawals. More generally, TransactionalRabbitPublisher registers a TransactionSynchronization.afterCommit callback, so RabbitMQ messages are sent only after the DB commits:

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
    @Override public void afterCommit() { rabbitTemplate.convertAndSend(exchange, key, payload); }
});
SperoTek (in dev)ledger/api/JournalPosted · company/api/CompanyCreated · approvals/api/ApprovalDecided · identity/api/UserDeletionRequested

Events are the way modules talk. They’re public records in each module’s api/ package. Listeners use @ApplicationModuleListener, which is Spring Modulith’s shortcut for @Async + @Transactional(REQUIRES_NEW) + @TransactionalEventListener(AFTER_COMMIT). Each listener runs after commit, in its own transaction, on another thread. Events are also persisted in the event publication registry (next lesson), so they survive crashes.

Alternatives

Option Notes
Direct method calls Simple, but couples the modules
Spring application events (yours) In-process, simple; lost on crash unless persisted
Spring Modulith persistent events (SperoTek) Crash-safe, with republish on restart
Message broker Cross-process and cross-service
Event sourcing Events are the database (bonus module)
  • Events vs commands. SendEmail is a command (do this), and JournalPosted is an event (this happened). SperoTek has both.
  • Event payloads. Carry ids and key facts, not whole entities, because an entity is detached by the time an AFTER_COMMIT listener runs.
  • Ordering and idempotency. Listeners may run more than once after republishing, so make them idempotent.
  • Testing. Spring Modulith’s Scenario API and @RecordApplicationEvents let you assert that events were published.

Check yourself

1. An @EventListener (not transactional) throws. The publishing transaction…
2. @ApplicationModuleListener combines…
3. Gap in plain AFTER_COMMIT listeners?