Simple definition#
Spring’s application events let one bean publish a message (“an order was placed”) and any number of other beans listen and react, without the publisher knowing them. It is the Observer pattern, implemented by the ApplicationContext, inside one application.
The problem#
OrderService should not have to call EmailService, LoyaltyService, AnalyticsService and InventoryService directly. Every new reaction would mean changing and re-testing the order code, and the service would accumulate unrelated dependencies.
Publishing and listening#
public record OrderPlaced(String orderId, String customerId, BigDecimal total) {} // any object can be an event
@Service
class OrderService {
private final ApplicationEventPublisher events;
OrderService(ApplicationEventPublisher events) { this.events = events; }
@Transactional
public Order place(PlaceOrder cmd) {
Order order = repository.save(Order.from(cmd));
events.publishEvent(new OrderPlaced(order.id(), order.customerId(), order.total()));
return order;
}
}
@Component
class LoyaltyListener {
@EventListener
@Order(10)
void on(OrderPlaced event) { loyalty.addPoints(event.customerId(), event.total()); }
@EventListener(condition = "#event.total > 1000") // SpEL condition
void onLarge(OrderPlaced event) { alerts.notifyVipTeam(event); }
}
A listener can also return a new event (or a collection of them), which Spring publishes in turn.
Synchronous by default#
sequenceDiagram
participant S as OrderService (@Transactional)
participant P as ApplicationEventMulticaster
participant L1 as LoyaltyListener
participant L2 as EmailListener
S->>P: publishEvent(OrderPlaced)
P->>L1: on(event) (same thread, same tx)
P->>L2: on(event)
L2--xP: exception
P--xS: exception propagates and the transaction rolls back- Listeners run one after another in the publisher’s thread, inside its transaction.
- A listener exception propagates to the publisher.
- That is simple and consistent, but slow listeners slow the request, and failures in side effects (email) roll back business data.
@TransactionalEventListener#
Often you want to react only if the transaction commits:
@Component
class EmailListener {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) // default phase
@Async
void sendConfirmation(OrderPlaced event) { mail.sendOrderConfirmation(event.orderId()); }
}
| Phase | Runs | Use |
|---|---|---|
BEFORE_COMMIT | Just before commit, inside the transaction | Last-moment checks or writes |
AFTER_COMMIT (default) | After a successful commit | Emails, cache eviction, notifications |
AFTER_ROLLBACK | After a rollback | Compensation and alerts |
AFTER_COMPLETION | After either | Cleanup |
Asynchronous listeners#
- Add
@Async(and@EnableAsync) to run a listener on a task executor. Withspring.threads.virtual.enabled=true, that executor uses virtual threads. - Async listeners do not share the publisher’s transaction or thread-locals (security context, MDC), so propagate context explicitly if needed.
- Exceptions go to an
AsyncUncaughtExceptionHandler. Log and alert.
Built-in lifecycle events#
| Event | When |
|---|---|
ApplicationStartingEvent … ApplicationPreparedEvent | Early Boot startup stages (register these via spring.factories or SpringApplication) |
ContextRefreshedEvent | The context is initialised or refreshed |
ApplicationStartedEvent | Context refreshed, before the runners |
ApplicationReadyEvent | Ready to serve: the good place for warm-up tasks |
AvailabilityChangeEvent | Liveness and readiness changes (Kubernetes probes) |
ContextClosedEvent | Shutdown begins |
Spring Modulith: reliable in-process events#
Spring Modulith adds an event publication registry. Events for @ApplicationModuleListeners are stored in the database in the same transaction as the business change, then delivered after commit and marked complete. Incomplete publications are retried on restart. It can also externalise events to Kafka, RabbitMQ or SQS. This is the bridge from in-process events to a message broker.
@ApplicationModuleListener // = @Async + @Transactional(REQUIRES_NEW) + @TransactionalEventListener
void on(OrderPlaced event) { inventory.reserve(event.orderId()); }
Application events vs a message broker#
| Spring application events | Broker (Kafka, RabbitMQ) | |
|---|---|---|
| Scope | One JVM | Across services |
| Durability | In-memory, unless you use the Modulith registry | Durable |
| Use for | Decoupling modules inside an app (a modular monolith) | Integration between services |
Common mistakes#
Quick check#
Are Spring events synchronous by default? Yes. Listeners run in the publisher’s thread, in its transaction, and exceptions propagate to the publisher.
What does @TransactionalEventListener add?
It ties the listener to a transaction phase, by default running it only after a successful commit.
Why can AFTER_COMMIT reactions be lost? The event exists only in memory; a crash between commit and listener execution loses it.
What does Spring Modulith’s event publication registry provide? Events are persisted in the same transaction as the business change, then delivered and retried until completed.
When use a broker instead of application events? When events must cross service or process boundaries, or need durable, replayable delivery.
Summary#
- Application events decouple beans inside one app: the Observer pattern by the container.
- They are synchronous and transactional by default; use
@TransactionalEventListener(AFTER_COMMIT)plus@Asyncfor side effects. - For guaranteed delivery, use the Spring Modulith registry or an outbox; use brokers between services.
References#
- Spring Framework reference, Standard and Custom Events and Transaction-bound events.
- Spring Boot reference, Application Events and Listeners.
- Spring Modulith reference, Working with Application Events.