Application Events & Listeners
Spring's application events let one bean announce that something happened ("order placed") without knowing which beans react.
Introduction
Spring's application events let one bean announce that something happened ("order placed") without knowing which beans react. Listeners for inventory, email, loyalty, and fraud can be added or removed without touching the publisher.
By default, events are synchronous and in the same thread and transaction as the publisher. That default is the most important fact in this lesson.
Purpose of this lesson
You will publish domain events, order listeners, filter with SpEL conditions, chain events by returning values, and choose between synchronous, asynchronous, and transaction-bound listeners.
Understanding the topic
Event model:
- Any object can be an event — a Java
recordis ideal. Spring wraps non-ApplicationEventobjects in aPayloadApplicationEvent. - Publish with
ApplicationEventPublisher.publishEvent(event); inject the publisher like any other bean. - Listen with
@EventListeneron a bean method; the parameter type selects the events. @Ordersets the order between listeners; listeners without it run after ordered ones.condition = "#event.totalCents > 100000"filters with SpEL;#eventmust match the parameter name.- A listener that returns a non-null value publishes that value as a new event.
- Framework events such as
ContextRefreshedEventandContextClosedEventuse the same mechanism.
Production implementation
Choosing the delivery mode:
- Plain
@EventListener— same thread, same transaction. An exception in a listener propagates to the publisher and can roll back its transaction. @TransactionalEventListener(AFTER_COMMIT)— use for side effects (emails, messages) that must not happen if the transaction rolls back.@Asynclisteners — do not block the caller, but run outside the caller's transaction and lose its thread-local context.- In-memory events are lost if the process crashes. For guaranteed delivery between services, write an outbox row in the same transaction and publish to a broker.
@Componentclass OrderEventHandlers {// Runs only after the publishing transaction commits; skipped on rollback.@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)void sendConfirmation(OrderPlaced e) { mailer.sendConfirmation(e.orderId()); }// Runs on a task executor thread; requires @EnableAsync on a configuration class.@Async@EventListenervoid warmRecommendations(OrderPlaced e) { recommender.refreshFor(e.orderId()); }}
Informative example
An order flow with four listeners (each class below is registered as a @Bean in an AppConfig):
public record OrderPlaced(String orderId, int totalCents) {}public record LoyaltyPointsEarned(String orderId, int points) {}public class OrderService {private final ApplicationEventPublisher events;public OrderService(ApplicationEventPublisher events) { this.events = events; }public void place(String orderId, int totalCents) {System.out.println("saved " + orderId);events.publishEvent(new OrderPlaced(orderId, totalCents));System.out.println("place() returned for " + orderId);}}public class InventoryListener {@EventListener @Order(1)public void reserve(OrderPlaced e) { System.out.println("inventory reserved for " + e.orderId()); }}public class EmailListener {@EventListener @Order(2)public void confirm(OrderPlaced e) { System.out.println("confirmation email for " + e.orderId()); }}public class FraudListener {@EventListener(condition = "#event.totalCents > 100000")public void review(OrderPlaced event) { System.out.println("fraud review for " + event.orderId()); }}public class LoyaltyListener {@EventListenerpublic LoyaltyPointsEarned award(OrderPlaced e) {return new LoyaltyPointsEarned(e.orderId(), e.totalCents() / 100);}@EventListenerpublic void print(LoyaltyPointsEarned e) { System.out.println(e.points() + " points for " + e.orderId()); }}public class StartupListener {@EventListenerpublic void ready(ContextRefreshedEvent e) { System.out.println("context refreshed"); }}public static void main(String[] args) {try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {OrderService orders = ctx.getBean(OrderService.class);orders.place("o-1", 4999);orders.place("o-2", 250000);}}
Output
context refreshed saved o-1 inventory reserved for o-1 confirmation email for o-1 49 points for o-1 place() returned for o-1 saved o-2 inventory reserved for o-2 confirmation email for o-2 fraud review for o-2 2500 points for o-2 place() returned for o-2
Notice that place() returned prints after every listener: the publisher waited for all of them. The fraud listener only ran for the 250,000-cent order because of its condition. Compile with -parameters (Spring Boot's build plugins do this for you) so SpEL can see the parameter name event.
Best practices
- Model events as immutable records named in the past tense (
OrderPlaced,PaymentCaptured). - Keep events small: identifiers and the facts listeners need, not whole entities.
- Use
AFTER_COMMITfor external side effects and an outbox for cross-service delivery. - Test listeners as plain methods, and test the wiring with one context test.
Common mistakes
- Sending email from a plain
@EventListenerand then rolling back — the customer gets a confirmation for an order that does not exist. - Assuming listeners are asynchronous — slow listeners make the publisher slow.
- Relying on the order of unordered listeners.
- Using a
@TransactionalEventListenerwhen no transaction is active — by default it is not invoked at all (setfallbackExecution = trueif you need that).
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionAre Spring application events synchronous or asynchronous?+
Answer
2IntermediateQuestionWhen would you use @TransactionalEventListener?+
Answer
Follow-up
Hands-on exercise
Hands-on: add a ShippingListener with @Order(3) and predict the new output before running it. Then make EmailListener throw an exception for order o-2 and observe that place() fails — finally move the email to a @TransactionalEventListener in a transactional service and explain the difference.
Summary
Application events decouple publishers from reactions. They are synchronous by default; use @TransactionalEventListener for commit-dependent side effects, @Async for background work, and an outbox when delivery must survive crashes.