Video in progress
Why do you need domain events, and how do you publish them in a Spring application?
A domain event is an important fact that happened in the domain ("the order was paid"). It decouples the aggregate from other modules: Order knows nothing about email, the warehouse or analytics, it just publishes an event. In Spring this is done with ApplicationEventPublisher and @TransactionalEventListener.
📖 Answer
A service without events:
order.markPaid(amount);
inventory.reserve(order);
mailer.sendReceipt(order);
analytics.track(order);
bonus.accrue(order);
Every new reaction changes PaymentService, and its dependencies keep growing.
With an event:
public record OrderPaid(OrderId orderId, Money amount, Instant at) {}
@Service
class PaymentService {
private final ApplicationEventPublisher events;
@Transactional
public void confirm(OrderId id, Money amount) {
var order = orders.getById(id);
order.markPaid(amount);
events.publishEvent(new OrderPaid(id, amount, Instant.now()));
}
}
@Component
class ReceiptMailer {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void on(OrderPaid e) { ... }
}
Traps:
@EventListeneris synchronous and runs in the same transaction, so an error in the listener also rolls back the payment. That is often not what you want.AFTER_COMMITruns only if the transaction succeeded, but if the application dies in between, the event is lost. For money or an important integration you need a transactional outbox: the event is written to a table in the same transaction, and a background job sends it later.- If you need to write to the DB inside an
AFTER_COMMITlistener, add@Transactional(propagation = REQUIRES_NEW), because the old transaction has already committed. - Spring Data also has
@DomainEvents/AbstractAggregateRoot.registerEvent()inside the aggregate; the events are published whensave()is called.
Name events in the past tense: OrderPaid, not PayOrder. It is a fact, not a command.
Sign up to mark studied questions and save your progress.