Video in progress

Strong Middle 🌱 Spring

How does @TransactionalEventListener work, and what traps does it have?

The listener doesn't run the moment the event is published, but when the transaction reaches the required phase (AFTER_COMMIT by default). If there is no transaction, by default it is not called at all.

📖 Answer

@Component
class OrderListeners {
    @TransactionalEventListener                // AFTER_COMMIT
    void notify(OrderPaid e) { sms.send(e.phone(), "To'lov qabul qilindi"); }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
    void alert(OrderPaid e) { log.warn("Payment rolled back {}", e.orderId()); }
}

The phases: BEFORE_COMMIT, AFTER_COMMIT, AFTER_ROLLBACK, AFTER_COMPLETION.

The most common trap: if the event is published without a transaction, the listener is silently skipped. If you need it to run, set fallbackExecution = true.

Another subtle spot: writing to the database inside AFTER_COMMIT. The transaction has already committed, but the resources are still bound to the thread, so a plain save may write nothing. If you need to write, put @Transactional(propagation = REQUIRES_NEW) on the listener.

An exception in the listener does not cancel the main operation: it has already committed, and the error only goes to the log. If the application dies after the commit, the listener never runs at all; for important external effects you need an outbox.

It is usually used for clearing a cache, sending a notification, or giving another system a "best effort" signal.