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 Publishing an event and listening for it A failing listener stops the publisher Choosing which events a listener receives Asynchronous listeners with @Async Events tied to a transaction: @TransactionalEventListener Writing to the database after commit Generic events need a resolvable type Events Spring publishes itself Choosing the right kind of listener
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
and callApplicationEventPublisher . The application context itself is the publisher. Since Spring Framework 4.2 the event can be any object, such as a record; older code extendspublishEvent(event) .ApplicationEvent - The listeners: methods annotated with
, or beans that implement@EventListener . At startup Spring reads each listener's parameter type and registers it for that type and its subtypes.ApplicationListener<E> - The multicaster:
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, beforeSimpleApplicationEventMulticaster returns.publishEvent
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.
| API | Since | Runs | Best for |
|---|---|---|---|
ApplicationListener<E> | 1.0 | On the publisher's thread | Framework code and listeners registered as lambdas |
@EventListener | 4.2 | On the publisher's thread | Most application listeners |
@EventListener@Async | 4.2 | On an executor thread | Slow side work the publisher should not wait for |
@TransactionalEventListener | 4.2 | At a transaction phase, by default after commit | Reactions 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
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:
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");
}
}
}
[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,
, with no Spring type in it. Spring wraps it in aOrderPlaced internally, and the listeners receive the record itself.PayloadApplicationEvent - Both listeners ran on
, between "saving order" and "publishEvent returned". The publisher waited for them, exactly as if it had called them directly.main does not know thatOrderService orEmailListener exist. That is the benefit: either listener can be removed, or a third added, without touching the service.StockListener
The listeners ran email first here, but without @Order
A failing listener stops the publisher
Because listeners run inside publishEvent
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());
}
}
}
}
publishEvent(UserRegistered):
1. profile created for ada@example.com
2. mail server down, throwing
publisher sees: SMTP connection refused
ran and created the profile.@Order(1) threw, and listener 3 never ran: the user got no trial credits.@Order(2) 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.publishEvent
A listener that throws a checked exception has it wrapped in UndeclaredThrowableExceptionpublishEventErrorHandlersetErrorHandler
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:
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"));
}
}
}
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
received all three events, because bothaudit(PaymentEvent) andPaymentReceived implement that interface.PaymentFailed is a SpEL expression evaluated before the call. Only the 250000-cent payment printed "fraud check".condition = "#event.cents >= 100000" returned anship , and Spring published it as a new event.OrderShipped returned aafterShipping , and each element was published separately: anList and a plainInvoiceRequested , which reached theString listener.String- 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
printed after billing.OrderShipped takes no parameter and listens for both types. It printed once per order: for@EventListener({PaymentFailed.class, OrderShipped.class}) after orders 1 and 2, and forOrderShipped for order 3.PaymentFailed
The #eventjavac -parameters#root.event
Asynchronous listeners with @Async
Building a report takes time that the user should not wait for. Adding @Async@EnableAsync
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);
}
}
}
[main] publishing
[main] publishEvent returned at once
[report-2] handler got: archive offline from uploadToArchive
[report-1] PDF built for sales-2026-10
printed before either listener finished. The PDF listener ran onpublishEvent returned at once , a thread from the executor named inreport-1 .AsyncConfigurer- The archive listener threw on
, and the publisher never saw it. The exception went to thereport-2 . Without one, Spring only logs it.AsyncUncaughtExceptionHandler
Async listeners trade safety for speed. They cannot return a value to publish a follow-up event; inject ApplicationEventPublisher
To make every listener asynchronous, give the context a bean named applicationEventMulticasterSimpleApplicationEventMulticastersetTaskExecutor@Async
Events tied to a transaction: @TransactionalEventListener
A welcome email for an account that was rolled back is a real bug. @TransactionalEventListener
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));
}
}
}
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
ran at once, inside the open transaction. The two@EventListener listeners ran only after the commit, so the welcome mail for ada went out for an account that exists.AFTER_COMMIT - 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
listeners did not run, andAFTER_COMMIT did.AFTER_ROLLBACK - Case 3: with no transaction, the default
silently dropped the event. Only the listener with@TransactionalEventListener ran. Accounts ada and cy were saved; bob was not.fallbackExecution = true
The phases are BEFORE_COMMITAFTER_COMMITAFTER_ROLLBACKAFTER_COMPLETIONAFTER_COMMITTransactionSynchronization.afterCompletion threw exception
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
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
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));
}
}
}
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
write ran in a fresh transaction, which rolled back properly: its row is gone.REQUIRES_NEW - The
write threw too, yet its rowREQUIRED 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.REQUIRED, order 7
The fix is the one the Javadoc gives: use Propagation.REQUIRES_NEW@Transactional@TransactionalEventListener@TransactionalEventListener method must not be annotated with @Transactional unless when declared as REQUIRES_NEW or NOT_SUPPORTEDREQUIRED
Generic events need a resolvable type
A single Created<T>Created<Customer>Created<Product>
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")));
}
}
}
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
events reached no listener at all, not evenCreated . The event's run-time type is plaincustomerCreated , and Spring does not match it againstCreated . Nothing is logged, so the mistake is silent.Created<Customer> implementsTypedCreated and reports its full type from the entity inside it. Each event then went to the matching listener only: Ada to the customer listener,ResolvableTypeProvider to the product listener.pen-01
A subclass that fixes the type argument, such as class CustomerCreated extends Created<Customer>ResolvableTypeProvider
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:
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();
}
}
new AnnotationConfigApplicationContext(...):
LifecycleLogger constructed
refreshed: 7 bean definitions, all singletons ready
start() and stop():
ContextStartedEvent
ContextStoppedEvent
close():
ApplicationListener: context closing
@EventListener: context closing
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, theContextRefreshedEvent class and Spring's own annotation processors.Config andContextStartedEvent appeared only because the program calledContextStoppedEvent andstart() explicitly. A plain refresh does not publish them.stop() reached both the lambdaContextClosedEvent bean and theApplicationListener method. It arrives before singletons are destroyed, so beans can still be used while handling it.@EventListener
Spring Boot adds events around startup: ApplicationStartedEventApplicationReadyEventSpringApplication.addListeners
Choosing the right kind of listener
| Situation | Use |
|---|---|
| A reaction that must succeed or fail with the action | @EventListener |
| Slow side work the caller should not wait for | @Async@EventListenerAsyncUncaughtExceptionHandler |
| Email, cache eviction or notifications after saved data | @TransactionalEventListenerAFTER_COMMIT |
| The same, when the event may be published without a transaction | Add fallbackExecution = true |
| Database writes from an after-commit listener | A @Transactional(propagation = REQUIRES_NEW) |
| Only some events of a type | condition |
| One generic event for many entity types | ResolvableTypeProvider |
| A reaction that must survive a crash, or reach another service | A 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