The publisher does not know who listens, which keeps a growing side-effect list out of the core method.
record OrderPlaced(Long orderId) { }
@Service
class OrderService {
private final ApplicationEventPublisher events;
void place(Order o) {
repo.save(o);
events.publishEvent(new OrderPlaced(o.getId()));
}
}
@Component
class EmailListener {
@TransactionalEventListener(phase = AFTER_COMMIT)
void on(OrderPlaced e) { mail.send(e.orderId()); }
}
The email is only sent once the order transaction has COMMITTED,
so a rolled-back order never sends a confirmation.
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11