Spring has a built-in event mechanism: a component publishes an event with ApplicationEventPublisher, and any bean method annotated with @EventListener receives it. Since Spring 4.2 an event can be any object, so a Java record works well and you no longer need to extend ApplicationEvent. Listeners run synchronously in the publisher's thread by default, and you can make them asynchronous or tie them to a transaction phase.
Events decouple the code that does something from the code that reacts to it, for example sending an email after an order is placed, without the order service knowing about email.
Create the event as a plain type. A record is ideal because events are immutable facts.
Inject ApplicationEventPublisher and call publishEvent.
ApplicationEventPublisher is implemented by the ApplicationContext, so it can be injected into any bean through the constructor. If you pass a non-ApplicationEvent object, Spring wraps it in a PayloadApplicationEvent and delivers it to listeners whose parameter type matches.
Annotate a method on any Spring bean. The parameter type decides which events it receives.
The condition attribute takes a SpEL expression, evaluated against the event. A listener can also return a value: if it returns a non-null object, Spring publishes that object as a new event, which is a simple way to chain steps. When several listeners handle the same event, order them with @Order.
Because default dispatch is synchronous, the listener runs inside the publisher's thread and transaction, and an exception in the listener propagates to the publisher.
To avoid blocking the publisher, enable async support and annotate the listener with @Async.
Be aware of the trade-offs:
AsyncUncaughtExceptionHandler.spring.threads.virtual.enabled=true so the default executor uses virtual threads.An alternative is registering an ApplicationEventMulticaster bean with an executor, but that makes every listener asynchronous, so @Async per listener is usually clearer.
If a listener sends an email or calls another system, it should only run when the order is really committed. Use @TransactionalEventListener.
| Phase | Runs |
|---|---|
BEFORE_COMMIT | Just before the commit |
AFTER_COMMIT (default) | After a successful commit |
AFTER_ROLLBACK | After a rollback |
AFTER_COMPLETION | After either outcome |
If no transaction is active, the event is dropped unless you set fallbackExecution = true. Also note that in AFTER_COMMIT the transaction has completed, so database writes made there need @Transactional(propagation = Propagation.REQUIRES_NEW) on the listener. Since Spring 6.1, an @Async combination with transactional events is handled the same way, but the REQUIRES_NEW rule still applies.
Spring publishes events for the container lifecycle, which you can listen to the same way.
| Event | When it fires |
|---|---|
ContextRefreshedEvent | Context initialised or refreshed |
ContextStartedEvent / ContextStoppedEvent | start() and stop() called on the context |
ContextClosedEvent | Context closing |
ApplicationReadyEvent (Spring Boot) | Application started and ready to serve |
For Boot start-up work, ApplicationReadyEvent is usually preferable to ContextRefreshedEvent, which can fire more than once in a hierarchy of contexts.
Spring Boot Test provides @RecordApplicationEvents to assert what was published.
No. Since Spring 4.2 any object can be an event. Records and plain classes are the normal choice today.
Yes by default. The listener runs in the publisher's thread. Add @Async or use a custom multicaster to make delivery asynchronous.
No. They work inside one application context and in memory, with no persistence or delivery guarantee. Use Kafka, RabbitMQ or similar between services.
@TransactionalEventListener not called?The event was probably published outside an active transaction. Publish inside a @Transactional method or set fallbackExecution = true.
Publish events through ApplicationEventPublisher, receive them with @EventListener, and use records as event types. Add @Async when the reaction must not block the caller, and @TransactionalEventListener when it must happen only after a commit. Remember that Spring events are in-process and in-memory, and use a broker when you need events across services.