Spring application events: how they are delivered and where they go wrong

Spring events let one bean announce that something happened while others react, without knowing each other. By default they are plain method calls on the publisher's thread, which decides how exceptions, threads and transactions behave. This page runs every kind of listener with Spring Framework 7.0, including the traps that send emails for data that was never saved.

Contents

How Spring application events work

An application event is an object that one part of the application publishes and other parts react to, without the publisher knowing who they are. An order service publishes "order placed"; an email listener, a stock listener and an audit listener each pick it up. Adding a fourth reaction means adding a fourth listener, not changing the order service.

Three pieces make it work, all inside one Spring ApplicationContext:

  • The publisher: any bean can inject ApplicationEventPublisher and call publishEvent(event). The application context itself is the publisher. Since Spring Framework 4.2 the event can be any object, such as a record; older code extends ApplicationEvent.
  • The listeners: methods annotated with @EventListener, or beans that implement ApplicationListener<E>. At startup Spring reads each listener's parameter type and registers it for that type and its subtypes.
  • The multicaster: SimpleApplicationEventMulticaster receives every published event, finds the listeners whose type matches, and calls them one after another. Unless you configure it otherwise, it calls them on the publisher's thread, before publishEvent returns.

That last point surprises many developers. Events look like messaging, but by default they are plain method calls with the caller and callee decoupled. They share the publisher's thread, its transaction and its exceptions, and they disappear if the JVM stops. They are not a message broker: nothing is stored, and nothing is delivered to another service.

Ways to listen for events
APISinceRunsBest for
ApplicationListener<E>1.0On the publisher's threadFramework code and listeners registered as lambdas
@EventListener4.2On the publisher's threadMost application listeners
@EventListener with @Async4.2On an executor threadSlow side work the publisher should not wait for
@TransactionalEventListener4.2At a transaction phase, by default after commitReactions that must only happen if the data was saved

Every program on this page runs Spring Framework 7.0 without Spring Boot. Boot adds its own events, such as ApplicationReadyEvent, but publishes and delivers them with the same machinery.

Publishing an event and listening for it

An order is the usual example: one action, several independent reactions. Each line prints the thread it runs on, which shows where the listeners really run:

Java
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

public class EventBasics {

    record OrderPlaced(int orderId, String customer) {
    }

    @Configuration
    static class Config {
        @Bean
        OrderService orderService(ApplicationEventPublisher publisher) {
            return new OrderService(publisher);
        }

        @Bean
        EmailListener emailListener() {
            return new EmailListener();
        }

        @Bean
        StockListener stockListener() {
            return new StockListener();
        }
    }

    static class OrderService {
        private final ApplicationEventPublisher publisher;

        OrderService(ApplicationEventPublisher publisher) {
            this.publisher = publisher;
        }

        void placeOrder(int id, String customer) {
            System.out.println("[" + Thread.currentThread().getName() + "] saving order " + id);
            publisher.publishEvent(new OrderPlaced(id, customer));
            System.out.println("[" + Thread.currentThread().getName()
                    + "] publishEvent returned, placeOrder finishes");
        }
    }

    static class EmailListener {
        @EventListener
        void sendConfirmation(OrderPlaced event) {
            System.out.println("[" + Thread.currentThread().getName() + "] email to "
                    + event.customer() + " for order " + event.orderId());
        }
    }

    static class StockListener {
        @EventListener
        void reserveStock(OrderPlaced event) {
            System.out.println("[" + Thread.currentThread().getName()
                    + "] stock reserved for order " + event.orderId());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            context.getBean(OrderService.class).placeOrder(1001, "ada@example.com");
        }
    }
}
Output
[main] saving order 1001
[main] email to ada@example.com for order 1001
[main] stock reserved for order 1001
[main] publishEvent returned, placeOrder finishes
  • The event is a record, OrderPlaced, with no Spring type in it. Spring wraps it in a PayloadApplicationEvent internally, and the listeners receive the record itself.
  • Both listeners ran on main, between "saving order" and "publishEvent returned". The publisher waited for them, exactly as if it had called them directly.
  • OrderService does not know that EmailListener or StockListener exist. That is the benefit: either listener can be removed, or a third added, without touching the service.

The listeners ran email first here, but without @Order the order between listeners is not something to rely on.

A failing listener stops the publisher

Because listeners run inside publishEvent, an exception in one of them travels back to the publisher. Three listeners react to a new user, and the second one fails:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;

public class ListenerFailure {

    record UserRegistered(String email) {
    }

    @Configuration
    static class Config {
        @Bean
        Listeners listeners() {
            return new Listeners();
        }
    }

    static class Listeners {
        @EventListener
        @Order(1)
        void createProfile(UserRegistered event) {
            System.out.println("  1. profile created for " + event.email());
        }

        @EventListener
        @Order(2)
        void sendWelcomeEmail(UserRegistered event) {
            System.out.println("  2. mail server down, throwing");
            throw new IllegalStateException("SMTP connection refused");
        }

        @EventListener
        @Order(3)
        void grantTrialCredits(UserRegistered event) {
            System.out.println("  3. trial credits granted");
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            System.out.println("publishEvent(UserRegistered):");
            try {
                context.publishEvent(new UserRegistered("ada@example.com"));
                System.out.println("publisher continues");
            } catch (IllegalStateException e) {
                System.out.println("publisher sees: " + e.getMessage());
            }
        }
    }
}
Output
publishEvent(UserRegistered):
  1. profile created for ada@example.com
  2. mail server down, throwing
publisher sees: SMTP connection refused
  • @Order(1) ran and created the profile.
  • @Order(2) threw, and listener 3 never ran: the user got no trial credits.
  • publishEvent threw the listener's exception, so "publisher continues" was never printed. If the publisher was inside a transaction, that exception would roll it back too.

A listener that throws a checked exception has it wrapped in UndeclaredThrowableException, because publishEvent cannot declare checked exceptions. To keep one failing listener from affecting the others, catch inside the listener, run it asynchronously, or give the multicaster an ErrorHandler with setErrorHandler, which then logs or handles each listener's exception and moves on to the next.

Choosing which events a listener receives

A listener gets every event whose type matches its parameter, so the event type hierarchy controls routing. This program uses a sealed payment hierarchy, a condition, two listeners that return new events, and a listener declared for two unrelated types:

Java
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

public class EventRouting {

    sealed interface PaymentEvent permits PaymentReceived, PaymentFailed {
        int orderId();
    }

    record PaymentReceived(int orderId, long cents) implements PaymentEvent {
    }

    record PaymentFailed(int orderId, String reason) implements PaymentEvent {
    }

    record OrderShipped(int orderId) {
    }

    record InvoiceRequested(int orderId) {
    }

    @Configuration
    static class Config {
        @Bean
        Listeners listeners() {
            return new Listeners();
        }
    }

    static class Listeners {
        @EventListener
        void audit(PaymentEvent event) {
            System.out.println("  audit           : " + event);
        }

        @EventListener(condition = "#event.cents >= 100000")
        void flagLargePayment(PaymentReceived event) {
            System.out.println("  fraud check     : order " + event.orderId() + " is large");
        }

        @EventListener
        OrderShipped ship(PaymentReceived event) {
            System.out.println("  warehouse       : shipping order " + event.orderId());
            return new OrderShipped(event.orderId());
        }

        @EventListener
        List<Object> afterShipping(OrderShipped event) {
            System.out.println("  after shipping  : order " + event.orderId());
            return List.of(new InvoiceRequested(event.orderId()), "a plain String event");
        }

        @EventListener
        void invoice(InvoiceRequested event) {
            System.out.println("  billing         : invoice for order " + event.orderId());
        }

        @EventListener
        void strings(String text) {
            System.out.println("  String listener : " + text);
        }

        @EventListener({PaymentFailed.class, OrderShipped.class})
        void notifyCustomer() {
            System.out.println("  customer notice : sent");
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            System.out.println("PaymentReceived(1, 2500):");
            context.publishEvent(new PaymentReceived(1, 2500));
            System.out.println("PaymentReceived(2, 250000):");
            context.publishEvent(new PaymentReceived(2, 250000));
            System.out.println("PaymentFailed(3):");
            context.publishEvent(new PaymentFailed(3, "card expired"));
        }
    }
}
Output
PaymentReceived(1, 2500):
  audit           : PaymentReceived[orderId=1, cents=2500]
  warehouse       : shipping order 1
  after shipping  : order 1
  billing         : invoice for order 1
  String listener : a plain String event
  customer notice : sent
PaymentReceived(2, 250000):
  audit           : PaymentReceived[orderId=2, cents=250000]
  fraud check     : order 2 is large
  warehouse       : shipping order 2
  after shipping  : order 2
  billing         : invoice for order 2
  String listener : a plain String event
  customer notice : sent
PaymentFailed(3):
  audit           : PaymentFailed[orderId=3, reason=card expired]
  customer notice : sent
  • audit(PaymentEvent) received all three events, because both PaymentReceived and PaymentFailed implement that interface.
  • condition = "#event.cents >= 100000" is a SpEL expression evaluated before the call. Only the 250000-cent payment printed "fraud check".
  • ship returned an OrderShipped, and Spring published it as a new event. afterShipping returned a List, and each element was published separately: an InvoiceRequested and a plain String, which reached the String listener.
  • The returned events were published as soon as each listener returned, before the remaining listeners of the original event ran. That is why "customer notice" for OrderShipped printed after billing.
  • @EventListener({PaymentFailed.class, OrderShipped.class}) takes no parameter and listens for both types. It printed once per order: for OrderShipped after orders 1 and 2, and for PaymentFailed for order 3.

The #event name needs the code compiled with javac -parameters, which the Spring Boot build plugins switch on. #root.event works without it. Chained events are convenient but hard to follow when they grow: three hops are usually the most a reader can trace without a debugger.

Asynchronous listeners with @Async

Building a report takes time that the user should not wait for. Adding @Async to a listener moves it to an executor thread, provided @EnableAsync is on a configuration class. This program has one slow listener and one that fails:

Java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

public class AsyncListeners {

    record ReportRequested(String name) {
    }

    static final CountDownLatch DONE = new CountDownLatch(2);

    @Configuration
    @EnableAsync
    static class Config implements AsyncConfigurer {
        @Override
        public Executor getAsyncExecutor() {
            return new SimpleAsyncTaskExecutor("report-");
        }

        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return (error, method, params) -> {
                System.out.println("[" + Thread.currentThread().getName() + "] handler got: "
                        + error.getMessage() + " from " + method.getName());
                DONE.countDown();
            };
        }

        @Bean
        ReportListeners reportListeners() {
            return new ReportListeners();
        }
    }

    static class ReportListeners {
        @Async
        @EventListener
        public void buildPdf(ReportRequested event) throws InterruptedException {
            Thread.sleep(200);
            System.out.println("[" + Thread.currentThread().getName() + "] PDF built for "
                    + event.name());
            DONE.countDown();
        }

        @Async
        @EventListener
        public void uploadToArchive(ReportRequested event) {
            throw new IllegalStateException("archive offline");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            System.out.println("[" + Thread.currentThread().getName() + "] publishing");
            context.publishEvent(new ReportRequested("sales-2026-10"));
            System.out.println("[" + Thread.currentThread().getName()
                    + "] publishEvent returned at once");
            DONE.await(5, TimeUnit.SECONDS);
        }
    }
}
Output
[main] publishing
[main] publishEvent returned at once
[report-2] handler got: archive offline from uploadToArchive
[report-1] PDF built for sales-2026-10
  • publishEvent returned at once printed before either listener finished. The PDF listener ran on report-1, a thread from the executor named in AsyncConfigurer.
  • The archive listener threw on report-2, and the publisher never saw it. The exception went to the AsyncUncaughtExceptionHandler. Without one, Spring only logs it.

Async listeners trade safety for speed. They cannot return a value to publish a follow-up event; inject ApplicationEventPublisher and publish it instead. They do not run in the publisher's transaction. And if the application stops while the executor queue holds work, that work is lost. The Spring @Async page covers executors and their sizing.

To make every listener asynchronous, give the context a bean named applicationEventMulticaster of type SimpleApplicationEventMulticaster and call setTaskExecutor on it. That also makes Spring's own events asynchronous, so a per-listener @Async is usually the safer choice.

Events tied to a transaction: @TransactionalEventListener

A welcome email for an account that was rolled back is a real bug. @TransactionalEventListener holds the event until the publisher's transaction finishes, and then delivers it only in the phase you choose. The program opens one account that commits, one that rolls back, and one without any transaction:

Java
import javax.sql.DataSource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

public class TxEvents {

    record AccountOpened(String owner) {
    }

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:txevents;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE accounts (owner VARCHAR(20) PRIMARY KEY)");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        AccountService accountService(JdbcTemplate jdbc, ApplicationEventPublisher publisher) {
            return new AccountService(jdbc, publisher);
        }

        @Bean
        Listeners listeners() {
            return new Listeners();
        }
    }

    static class AccountService {
        private final JdbcTemplate jdbc;
        private final ApplicationEventPublisher publisher;

        AccountService(JdbcTemplate jdbc, ApplicationEventPublisher publisher) {
            this.jdbc = jdbc;
            this.publisher = publisher;
        }

        @Transactional
        public void open(String owner, boolean failAfterPublish) {
            jdbc.update("INSERT INTO accounts VALUES (?)", owner);
            publisher.publishEvent(new AccountOpened(owner));
            System.out.println("  event published, transaction still open");
            if (failAfterPublish) {
                throw new IllegalStateException("credit check failed");
            }
        }

        public void openWithoutTransaction(String owner) {
            jdbc.update("INSERT INTO accounts VALUES (?)", owner);
            publisher.publishEvent(new AccountOpened(owner));
        }
    }

    static class Listeners {
        @EventListener
        void immediately(AccountOpened event) {
            System.out.println("  @EventListener               : welcome mail for "
                    + event.owner());
        }

        @TransactionalEventListener
        void afterCommit(AccountOpened event) {
            System.out.println("  AFTER_COMMIT                 : welcome mail for "
                    + event.owner());
        }

        @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
        void afterRollback(AccountOpened event) {
            System.out.println("  AFTER_ROLLBACK               : cleanup for " + event.owner());
        }

        @TransactionalEventListener(fallbackExecution = true)
        void withFallback(AccountOpened event) {
            System.out.println("  AFTER_COMMIT, fallback = true: metrics for "
                    + event.owner());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            AccountService service = context.getBean(AccountService.class);
            System.out.println("1. Transaction commits:");
            service.open("ada", false);
            System.out.println("2. Transaction rolls back:");
            try {
                service.open("bob", true);
            } catch (IllegalStateException e) {
                System.out.println("  caller sees " + e.getMessage());
            }
            System.out.println("3. No transaction at all:");
            service.openWithoutTransaction("cy");
            System.out.println("Accounts: " + context.getBean(JdbcTemplate.class)
                    .queryForList("SELECT owner FROM accounts ORDER BY owner", String.class));
        }
    }
}
Output
1. Transaction commits:
  @EventListener               : welcome mail for ada
  event published, transaction still open
  AFTER_COMMIT                 : welcome mail for ada
  AFTER_COMMIT, fallback = true: metrics for ada
2. Transaction rolls back:
  @EventListener               : welcome mail for bob
  event published, transaction still open
  AFTER_ROLLBACK               : cleanup for bob
  caller sees credit check failed
3. No transaction at all:
  @EventListener               : welcome mail for cy
  AFTER_COMMIT, fallback = true: metrics for cy
Accounts: [ada, cy]
  • Case 1: the plain @EventListener ran at once, inside the open transaction. The two AFTER_COMMIT listeners ran only after the commit, so the welcome mail for ada went out for an account that exists.
  • Case 2: the plain listener again ran at once and sent a welcome mail for bob, whose account was then rolled back. That is the bug this annotation prevents. The AFTER_COMMIT listeners did not run, and AFTER_ROLLBACK did.
  • Case 3: with no transaction, the default @TransactionalEventListener silently dropped the event. Only the listener with fallbackExecution = true ran. Accounts ada and cy were saved; bob was not.

The phases are BEFORE_COMMIT, AFTER_COMMIT (the default), AFTER_ROLLBACK and AFTER_COMPLETION, which runs in both cases. An exception thrown by an AFTER_COMMIT listener does not reach the publisher: the data is already committed, so Spring logs the exception as TransactionSynchronization.afterCompletion threw exception and the caller returns normally. A scratch test confirmed this with Spring Framework 7.0.

After-commit delivery still lives only in memory. If the process dies between the commit and the listener, the email is never sent. When that matters, store the event in the same transaction as the data, as the transactional outbox page shows.

Writing to the database after commit

A listener that runs after commit often wants to write something of its own, such as an audit row. That runs into a rule documented on TransactionSynchronization.afterCommit: the original transaction's resources are still bound to the thread, so code that joins "the current transaction" joins one that has already committed. Here the audit check fails in both writes:

Java
import javax.sql.DataSource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;

public class AfterCommitWrites {

    record OrderPaid(int orderId) {
    }

    @Configuration
    @EnableTransactionManagement
    static class Config {
        @Bean
        DataSource dataSource() {
            return new DriverManagerDataSource("jdbc:h2:mem:aftercommit;DB_CLOSE_DELAY=-1");
        }

        @Bean
        JdbcTemplate jdbc(DataSource dataSource) {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY)");
            jdbc.execute("CREATE TABLE audit (entry VARCHAR(40))");
            return jdbc;
        }

        @Bean
        PlatformTransactionManager transactionManager(DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean
        OrderService orderService(JdbcTemplate jdbc, ApplicationEventPublisher publisher) {
            return new OrderService(jdbc, publisher);
        }

        @Bean
        AuditWriter auditWriter(JdbcTemplate jdbc) {
            return new AuditWriter(jdbc);
        }

        @Bean
        AuditListener auditListener(AuditWriter writer) {
            return new AuditListener(writer);
        }
    }

    static class OrderService {
        private final JdbcTemplate jdbc;
        private final ApplicationEventPublisher publisher;

        OrderService(JdbcTemplate jdbc, ApplicationEventPublisher publisher) {
            this.jdbc = jdbc;
            this.publisher = publisher;
        }

        @Transactional
        public void pay(int orderId) {
            jdbc.update("INSERT INTO orders VALUES (?)", orderId);
            publisher.publishEvent(new OrderPaid(orderId));
        }
    }

    static class AuditWriter {
        private final JdbcTemplate jdbc;

        AuditWriter(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional
        public void joinExisting(String entry) {
            jdbc.update("INSERT INTO audit VALUES (?)", entry);
            throw new IllegalStateException("audit check failed");
        }

        @Transactional(propagation = Propagation.REQUIRES_NEW)
        public void inNewTransaction(String entry) {
            jdbc.update("INSERT INTO audit VALUES (?)", entry);
            throw new IllegalStateException("audit check failed");
        }
    }

    static class AuditListener {
        private final AuditWriter writer;

        AuditListener(AuditWriter writer) {
            this.writer = writer;
        }

        @TransactionalEventListener
        void onPaid(OrderPaid event) {
            try {
                writer.joinExisting("REQUIRED, order " + event.orderId());
            } catch (IllegalStateException e) {
                System.out.println("listener: REQUIRED write threw " + e.getMessage());
            }
            try {
                writer.inNewTransaction("REQUIRES_NEW, order " + event.orderId());
            } catch (IllegalStateException e) {
                System.out.println("listener: REQUIRES_NEW write threw " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            context.getBean(OrderService.class).pay(7);
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            System.out.println("orders: "
                    + jdbc.queryForList("SELECT id FROM orders", Integer.class));
            System.out.println("audit : "
                    + jdbc.queryForList("SELECT entry FROM audit", String.class));
        }
    }
}
Output
listener: REQUIRED write threw audit check failed
listener: REQUIRES_NEW write threw audit check failed
orders: [7]
audit : [REQUIRED, order 7]
  • Both writes inserted a row and then threw, and the listener caught each exception.
  • The REQUIRES_NEW write ran in a fresh transaction, which rolled back properly: its row is gone.
  • The REQUIRED write threw too, yet its row REQUIRED, order 7 is still in the table. Its rollback did not undo the insert, because the insert went through a connection that belonged to the finished transaction.

The fix is the one the Javadoc gives: use Propagation.REQUIRES_NEW for any transactional work called from an after-commit listener. Since Spring Framework 6.1 Spring enforces part of this at startup. Putting @Transactional directly on a @TransactionalEventListener method fails the context with "@TransactionalEventListener method must not be annotated with @Transactional unless when declared as REQUIRES_NEW or NOT_SUPPORTED". The check does not see a REQUIRED method on another bean, as in this program, so that case is still up to you.

Generic events need a resolvable type

A single Created<T> event for every entity type is tempting, with one listener for Created<Customer> and another for Created<Product>. Java erases the type argument at run time, so Spring cannot see it unless the event tells it:

Java
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.ResolvableType;
import org.springframework.core.ResolvableTypeProvider;

public class GenericEvents {

    record Customer(String name) {
    }

    record Product(String sku) {
    }

    record Created<T>(T entity) {
    }

    record TypedCreated<T>(T entity) implements ResolvableTypeProvider {
        @Override
        public ResolvableType getResolvableType() {
            return ResolvableType.forClassWithGenerics(getClass(),
                    ResolvableType.forInstance(entity));
        }
    }

    @Configuration
    static class Config {
        @Bean
        Listeners listeners() {
            return new Listeners();
        }
    }

    static class Listeners {
        @EventListener
        void customerCreated(Created<Customer> event) {
            System.out.println("  Created<Customer> listener got " + event.entity());
        }

        @EventListener
        void customerTyped(TypedCreated<Customer> event) {
            System.out.println("  TypedCreated<Customer> listener got " + event.entity());
        }

        @EventListener
        void productTyped(TypedCreated<Product> event) {
            System.out.println("  TypedCreated<Product> listener got " + event.entity());
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            System.out.println("Publishing Created(Customer) and Created(Product):");
            context.publishEvent(new Created<>(new Customer("Ada")));
            context.publishEvent(new Created<>(new Product("pen-01")));
            System.out.println("Publishing TypedCreated(Customer) and TypedCreated(Product):");
            context.publishEvent(new TypedCreated<>(new Customer("Ada")));
            context.publishEvent(new TypedCreated<>(new Product("pen-01")));
        }
    }
}
Output
Publishing Created(Customer) and Created(Product):
Publishing TypedCreated(Customer) and TypedCreated(Product):
  TypedCreated<Customer> listener got Customer[name=Ada]
  TypedCreated<Product> listener got Product[sku=pen-01]
  • The two Created events reached no listener at all, not even customerCreated. The event's run-time type is plain Created, and Spring does not match it against Created<Customer>. Nothing is logged, so the mistake is silent.
  • TypedCreated implements ResolvableTypeProvider and reports its full type from the entity inside it. Each event then went to the matching listener only: Ada to the customer listener, pen-01 to the product listener.

A subclass that fixes the type argument, such as class CustomerCreated extends Created<Customer>, also works, because the type argument is then recorded in the class file. With records, which cannot be extended, ResolvableTypeProvider is the way.

Events Spring publishes itself

The application context publishes events at points in its own lifecycle, and listeners receive them like any other. The program creates, starts, stops and closes a context:

Java
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.EventListener;

public class ContextEvents {

    @Configuration
    static class Config {
        @Bean
        LifecycleLogger lifecycleLogger() {
            return new LifecycleLogger();
        }

        @Bean
        ApplicationListener<ContextClosedEvent> closeListener() {
            return event -> System.out.println("  ApplicationListener: context closing");
        }
    }

    static class LifecycleLogger {
        LifecycleLogger() {
            System.out.println("  LifecycleLogger constructed");
        }

        @EventListener
        void refreshed(ContextRefreshedEvent event) {
            System.out.println("  refreshed: " + event.getApplicationContext()
                    .getBeanDefinitionCount() + " bean definitions, all singletons ready");
        }

        @EventListener({ContextStartedEvent.class, ContextStoppedEvent.class})
        void startStop(Object event) {
            System.out.println("  " + event.getClass().getSimpleName());
        }

        @EventListener
        void closed(ContextClosedEvent event) {
            System.out.println("  @EventListener: context closing");
        }
    }

    public static void main(String[] args) {
        System.out.println("new AnnotationConfigApplicationContext(...):");
        var context = new AnnotationConfigApplicationContext(Config.class);
        System.out.println("start() and stop():");
        context.start();
        context.stop();
        System.out.println("close():");
        context.close();
    }
}
Output
new AnnotationConfigApplicationContext(...):
  LifecycleLogger constructed
  refreshed: 7 bean definitions, all singletons ready
start() and stop():
  ContextStartedEvent
  ContextStoppedEvent
close():
  ApplicationListener: context closing
  @EventListener: context closing
  • ContextRefreshedEvent arrived after the constructor ran and every singleton was created, which makes it a safe point to start work that needs the whole context. It reports 7 bean definitions: the 2 declared ones, the Config class and Spring's own annotation processors.
  • ContextStartedEvent and ContextStoppedEvent appeared only because the program called start() and stop() explicitly. A plain refresh does not publish them.
  • ContextClosedEvent reached both the lambda ApplicationListener bean and the @EventListener method. It arrives before singletons are destroyed, so beans can still be used while handling it.

Spring Boot adds events around startup: ApplicationStartedEvent after the context is refreshed, and ApplicationReadyEvent once the application is ready to serve requests, which is the usual place for warm-up work. A few Boot events fire before the context exists, so they need a listener registered with SpringApplication.addListeners rather than a bean. The bean lifecycle page shows where these fit among the bean callbacks.

Choosing the right kind of listener

Common event situations and what fits them
SituationUse
A reaction that must succeed or fail with the action@EventListener, on the publisher's thread and in its transaction
Slow side work the caller should not wait for@Async with @EventListener, and an AsyncUncaughtExceptionHandler
Email, cache eviction or notifications after saved data@TransactionalEventListener, default AFTER_COMMIT
The same, when the event may be published without a transactionAdd fallbackExecution = true
Database writes from an after-commit listenerA @Transactional(propagation = REQUIRES_NEW) method
Only some events of a typecondition with SpEL, or a narrower event type
One generic event for many entity typesResolvableTypeProvider
A reaction that must survive a crash, or reach another serviceA transactional outbox and a message broker, not application events

Four rules explain most event bugs: listeners run on the publisher's thread unless made async, a failing synchronous listener stops the publisher and later listeners, a plain listener runs before the transaction commits, and a @TransactionalEventListener without a transaction drops the event. Related pages: Spring @Transactional, Spring @Async and the transactional outbox pattern.