Spring Framework Tutorial 0/19 lessons ~6 min read Lesson 11

    Application Events & Listeners

    Spring's application events let one bean announce that something happened ("order placed") without knowing which beans react.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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 record is ideal. Spring wraps non-ApplicationEvent objects in a PayloadApplicationEvent.
    • Publish with ApplicationEventPublisher.publishEvent(event); inject the publisher like any other bean.
    • Listen with @EventListener on a bean method; the parameter type selects the events.
    • @Order sets the order between listeners; listeners without it run after ordered ones.
    • condition = "#event.totalCents > 100000" filters with SpEL; #event must match the parameter name.
    • A listener that returns a non-null value publishes that value as a new event.
    • Framework events such as ContextRefreshedEvent and ContextClosedEvent use 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.
    • @Async listeners — 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.
    java
    @Component
    class 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
    @EventListener
    void 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):

    java
    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 {
    @EventListener
    public LoyaltyPointsEarned award(OrderPlaced e) {
    return new LoyaltyPointsEarned(e.orderId(), e.totalCents() / 100);
    }
    @EventListener
    public void print(LoyaltyPointsEarned e) { System.out.println(e.points() + " points for " + e.orderId()); }
    }
    public class StartupListener {
    @EventListener
    public 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_COMMIT for 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 @EventListener and 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 @TransactionalEventListener when no transaction is active — by default it is not invoked at all (set fallbackExecution = true if you need that).

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    2 questions
    1BeginnerQuestionAre Spring application events synchronous or asynchronous?+

    Answer

    Synchronous by default: listeners run in the publisher's thread, inside its transaction, before publishEvent returns. You can make a listener asynchronous with @Async (and @EnableAsync) or bind it to a transaction phase with @TransactionalEventListener.
    2IntermediateQuestionWhen would you use @TransactionalEventListener?+

    Answer

    When a side effect must happen only if the transaction commits, such as sending an email or publishing a message after an order is saved. With AFTER_COMMIT the listener is skipped when the transaction rolls back.

    Follow-up

    What happens if the process crashes after the commit but before the listener runs? (The event is lost — use an outbox for guaranteed delivery.)

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.