Video in progress

What is the difference between `@EventListener` and `@TransactionalEventListener` in Spring?

@EventListener runs as soon as the event is published, on the same thread and inside the same transaction. @TransactionalEventListener is tied to the transaction state: by default it's called only after the commit succeeds.

📖 Answer

Both are Observer: the service emits an event and doesn't know who is listening.

@Transactional
public void register(SignupRequest r) {
    var user = users.save(new User(r.email()));
    events.publishEvent(new UserRegistered(user.getId()));
    // ... then something threw an exception -> rollback
}

If the listener is a plain @EventListener and sends a welcome email, the email goes out, but the user never gets written to the database. On top of that, an exception inside the listener also fails register, because it's all one call stack.

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void sendWelcome(UserRegistered e) {
    mail.sendWelcome(e.userId());
}

Now the email goes out only after the data has really been saved. The phases are BEFORE_COMMIT, AFTER_COMMIT (the default), AFTER_ROLLBACK, AFTER_COMPLETION.

Two traps:

  • if you publish where there's no active transaction, @TransactionalEventListener isn't called at all (unless you set fallbackExecution = true);
  • if you want to write to the database inside an AFTER_COMMIT listener, you need @Transactional(propagation = REQUIRES_NEW), because the old transaction is already closed.