You’ve probably heard both of these stories. You move email sending into an event, and then the database rolls back but the email still goes out. Or data saved in an AFTER_COMMIT listener never shows up in the database.

The cause is usually how you chose between @EventListener and @TransactionalEventListener, or a misunderstanding of the transaction phase. In this article, we use tests to check which listeners are called on commit, on rollback, and outside a transaction. We assume Spring Boot 3.x (Spring Framework 6.x) and Java 17 or later. Design concepts are covered in Decoupling Modules with ApplicationEvent, so this article sticks to the differences in behavior.

Quick Reference: Which One to Use

From the second row on, the table shows how @TransactionalEventListener behaves for each phase.

ListenerOn commitOn rollbackOutside a transactionWhen it is called
@EventListener○○○At the time of publishEvent
@TransactionalEventListener (AFTER_COMMIT, default)○×× (*)After commit
@TransactionalEventListener (AFTER_ROLLBACK)×○× (*)After rollback
@TransactionalEventListener (AFTER_COMPLETION)○○× (*)After completion
@TransactionalEventListener (BEFORE_COMMIT)○×× (*)Just before commit

* If you specify fallbackExecution = true and there is no transaction, the listener runs immediately at the time of publishEvent, whatever its phase. Watch out: this means even an AFTER_ROLLBACK listener gets called.

In short, @EventListener runs “the moment the event is published,” and @TransactionalEventListener runs “according to the outcome of the transaction.” Unless you add @Async, both run synchronously on the same thread as the publisher.

A simple rule of thumb: put irreversible work such as emails and external notifications in AFTER_COMMIT. Put work that must stay consistent within the same transaction in @EventListener or BEFORE_COMMIT.

Receiving the Same Event with Both Kinds of Listener

Let’s check that things really behave as the table says. We assume three dependencies: spring-boot-starter-data-jpa, H2, and Lombok. The entity is named PurchaseOrder so it isn’t confused with the @Order annotation.

@Entity
@Getter
@NoArgsConstructor
public class PurchaseOrder {
    @Id @GeneratedValue
    private Long id;
    private String item;
    public PurchaseOrder(String item) { this.item = item; }
}

@Entity
@Getter
@NoArgsConstructor
public class AuditLog {
    @Id @GeneratedValue
    private Long id;
    private Long orderId;
    public AuditLog(Long orderId) { this.orderId = orderId; }
}

public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {}
public interface AuditLogRepository extends JpaRepository<AuditLog, Long> {}

Since Spring 4.2, an event doesn’t need to extend ApplicationEvent, so a record is enough for the event itself.

public record OrderPlacedEvent(Long orderId) {}

@Service
@RequiredArgsConstructor
public class OrderService {
    private final PurchaseOrderRepository orderRepository;
    private final ApplicationEventPublisher publisher;

    @Transactional
    public void place(String item, boolean fail) {
        PurchaseOrder order = orderRepository.save(new PurchaseOrder(item));
        publisher.publishEvent(new OrderPlacedEvent(order.getId()));
        if (fail) throw new IllegalStateException("在庫不足");
    }

    public void placeWithoutTx() { // @Transactionalなし
        publisher.publishEvent(new OrderPlacedEvent(0L));
    }
}

Each listener just adds its name to a list. We leave @Transactional off this class (the reason comes later).

@Component
public class OrderEventRecorder {
    public final List<String> calls = new CopyOnWriteArrayList<>();

    @EventListener
    public void event(OrderPlacedEvent e) { calls.add("EVENT"); }

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void beforeCommit(OrderPlacedEvent e) { calls.add("BEFORE_COMMIT"); }

    @TransactionalEventListener // 省略時はAFTER_COMMIT
    public void afterCommit(OrderPlacedEvent e) { calls.add("AFTER_COMMIT"); }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
    public void afterRollback(OrderPlacedEvent e) { calls.add("AFTER_ROLLBACK"); }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMPLETION)
    public void afterCompletion(OrderPlacedEvent e) { calls.add("AFTER_COMPLETION"); }
}

Checking the Behavior with @SpringBootTest

The key point is to not put @Transactional on the test class. If you do, the test’s transaction is rolled back when the test ends, and AFTER_COMMIT is never called. For the basic test setup, see Writing Integration Tests with @SpringBootTest.

@SpringBootTest
class OrderEventTest {
    @Autowired OrderService orderService;
    @Autowired OrderEventRecorder recorder;

    @BeforeEach
    void setUp() { recorder.calls.clear(); }

    @Test
    void コミット時() {
        orderService.place("book", false);
        assertThat(recorder.calls).startsWith("EVENT", "BEFORE_COMMIT")
            .containsExactlyInAnyOrder("EVENT", "BEFORE_COMMIT", "AFTER_COMMIT", "AFTER_COMPLETION");
    }

    @Test
    void ロールバック時() {
        assertThatThrownBy(() -> orderService.place("book", true))
            .isInstanceOf(IllegalStateException.class);
        assertThat(recorder.calls)
            .containsExactlyInAnyOrder("EVENT", "AFTER_ROLLBACK", "AFTER_COMPLETION");
    }

    @Test
    void トランザクション外() {
        orderService.placeWithoutTx();
        assertThat(recorder.calls).containsExactly("EVENT");
    }
}

AFTER_COMMIT and AFTER_COMPLETION are both handled together inside the transaction synchronization’s afterCompletion callback. Their relative order depends on the listeners’ @Order and their registration order, so the test doesn’t check the order between them.

@EventListener Can’t Take Back an Email After a Rollback

Notice that EVENT was recorded even in the rollback test. @EventListener runs immediately inside publishEvent, so a later rollback can’t undo an email that has already gone out.

The problem also works the other way. Exceptions thrown by the listener reach the publisher directly, so a failed email can roll back the order itself.

Move external side effects to AFTER_COMMIT. However, if the process crashes right after the commit, the notification is lost. If delivery must be guaranteed, consider the Transactional Outbox pattern.

Listeners Not Called Outside a Transaction, and fallbackExecution

By default, a @TransactionalEventListener is not called when the event is published outside a transaction. No error is raised either, so this is easy to miss.

The usual causes are a missing @Transactional on the publisher, or a call from within the same class (self-invocation) that bypasses the proxy. Self-invocation is covered in detail in Understanding Transaction Management with @Transactional.

If you also want the listener to run outside a transaction, specify fallbackExecution.

@TransactionalEventListener(fallbackExecution = true)
public void notify(OrderPlacedEvent e) {
    // トランザクションがなければ即時実行される
}

In that case, you lose the guarantee that the listener runs after a commit.

Calling save in an AFTER_COMMIT Listener Doesn’t Persist to the DB

At the AFTER_COMMIT point, the original transaction has already been committed, but its resources are still bound to the thread. The Javadoc for TransactionSynchronization#afterCommit also notes that the transaction’s resources may still be active and accessible at this point. As a result, a save inside the listener (with the default REQUIRED propagation) joins the finished transaction and is never committed.

The fix is to start a new transaction with REQUIRES_NEW. Put the audit-log listener in a separate @Component from the recorder class above. Adding @Transactional turns the bean into a proxy, and the test could no longer read the calls field directly.

@Component
@RequiredArgsConstructor
public class AuditListener {
    private final AuditLogRepository auditLogRepository;

    @TransactionalEventListener
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void writeAudit(OrderPlacedEvent e) {
        auditLogRepository.save(new AuditLog(e.orderId()));
    }
}

Without @Transactional on the test class, data carries over between tests, so clear it every time in @BeforeEach.

@SpringBootTest
class AuditListenerTest {
    @Autowired OrderService orderService;
    @Autowired PurchaseOrderRepository orderRepository;
    @Autowired AuditLogRepository auditLogRepository;

    @BeforeEach
    void cleanUp() {
        auditLogRepository.deleteAll();
        orderRepository.deleteAll();
    }

    @Test
    void コミットすると監査ログが残る() {
        orderService.place("book", false);
        assertThat(auditLogRepository.count()).isEqualTo(1);
    }

    @Test
    void ロールバックすると監査ログは残らない() {
        assertThatThrownBy(() -> orderService.place("book", true))
            .isInstanceOf(IllegalStateException.class);
        assertThat(auditLogRepository.count()).isZero();
    }
}

There are three possible outcomes, depending on how you write the listener:

  • A plain save with no @Transactional → On any Spring Boot version, the first test gets 0 and fails. There’s no error at startup either, so the data “silently disappears”
  • With @Transactional (REQUIRED) → On Spring Boot 3.1 and earlier, the application starts and the data silently disappears in the same way. From 3.2 (Spring Framework 6.1) on, startup fails
  • With @Transactional(propagation = REQUIRES_NEW) → The save is committed in a new transaction and the test passes

So even on 3.2 and later, the startup check won’t catch a listener that is missing @Transactional altogether. Keep this in mind.

On 3.2 and later, if you add @Transactional with anything other than REQUIRES_NEW or NOT_SUPPORTED, startup fails with an error like this (excerpt):

java.lang.IllegalStateException: @TransactionalEventListener method must not be annotated with @Transactional unless when declared as REQUIRES_NEW or NOT_SUPPORTED: public void com.example.AuditListener.writeAudit(...)

The same check also catches @Transactional placed on the whole listener class instead of on the method.

An Exception in AFTER_COMMIT Doesn’t Roll Back the Original Work

If an AFTER_COMMIT listener throws an exception, the original transaction isn’t undone, because it has already been committed. In Spring Framework 6.x, AFTER_COMMIT listeners are called from the transaction synchronization’s afterCompletion callback. TransactionSynchronizationUtils logs any exception thrown there and then swallows it. From the outside, the publishing method appears to have completed normally.

BEFORE_COMMIT, on the other hand, runs before the commit, so an exception there rolls back the entire original transaction. For work whose failures you need to know about, catch exceptions inside the listener and log them or retry.

Combining with @Async

Adding @Async runs the listener on a separate thread, so the publisher doesn’t have to wait.

@Component
@RequiredArgsConstructor
public class OrderMailListener {
    private final MailClient mailClient; // メール送信用の自前クラス

    @Async
    @TransactionalEventListener
    public void sendMail(OrderPlacedEvent e) {
        mailClient.sendOrderMail(e.orderId());
    }
}

Combined with @EventListener, the listener still runs on rollback. It also runs on another thread before the commit, so the data saved by the publisher may not be visible yet.

Combined with AFTER_COMMIT, it runs on a separate thread after the commit. The original transaction isn’t bound to that thread, so a lone repository save commits in its own transaction. If you add @Transactional to the method to group several updates together, it’s safest to use REQUIRES_NEW. How the startup check in 6.1+ treats @Async listeners may differ between minor versions, and REQUIRES_NEW passes on every version.

Exceptions from a void @Async method go to the AsyncUncaughtExceptionHandler, not to the publisher.

@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("非同期処理に失敗: {}", method.getName(), ex);
    }
}

If you forget @EnableAsync, the listener silently keeps running synchronously. Thread pool configuration is covered in Implementing Asynchronous Processing with @Async.

When the Same Event Is Handled Twice

The cause is usually one of the following:

  • The same logic is written in both an @EventListener and a @TransactionalEventListener
  • The same logic runs in both AFTER_COMMIT and AFTER_COMPLETION
  • A @Component class is also registered through a @Bean method under a different bean name

An example of the last case: OrderMailListener is a @Component, and a configuration class also registers it as @Bean OrderMailListener orderMailSender(). The bean names differ, so both beans survive and you end up with two listeners.

To tell them apart, log this.hashCode() and the thread name inside the listener. Two different hash codes mean a duplicate bean, so check the count with getBeansOfType. Asserting the number of invocations in a test also keeps the problem from coming back.

Receiving a Built-in Event (ApplicationReadyEvent) with @EventListener

Here is a minimal example that runs code when startup completes.

@Slf4j
@Component
public class StartupLogger {
    @EventListener(ApplicationReadyEvent.class)
    public void onReady() {
        log.info("起動が完了しました");
    }
}

Built-in events have nothing to do with transactions, so @EventListener is all you need. For when to use this versus CommandLineRunner, see the article on CommandLineRunner and ApplicationRunner.

Summary

Put anything that must not run on rollback in AFTER_COMMIT, and add REQUIRES_NEW when a listener updates the database. The startup check in 3.2 and later won’t catch a missing @Transactional, so protect against that with tests. If a listener might be called from outside a transaction, decide deliberately whether to use fallbackExecution.

If you don’t want the publisher to wait, add @Async and set up a handler for its exceptions. If you still need guaranteed delivery, that’s when the Outbox pattern comes in. Try running the tests from the quick-reference section yourself first, and the differences should become clear.