Spring Boot events guide
Spring Boot events provide a mechanism for communication between different components of an application without creating direct dependencies between them.
Spring Boot uses the event publishing and listening mechanism provided by the Spring Framework. It is based on the Observer design pattern and allows you to implement loosely coupled, event-driven applications.
For example, when a user registers in an application, you might need to:
- Send a welcome email.
- Create an audit log.
- Notify an administrator.
- Initialize the user’s preferences.
- Update application statistics.
Instead of calling all these services directly from UserService, you can publish a UserRegisteredEvent and allow independent listeners to react to it.
1. How Spring Boot events work
There are three main components in the Spring event mechanism:
| Component | Responsibility |
|---|---|
| Event | Contains information about something that happened. |
| Event publisher | Publishes an event using ApplicationEventPublisher. |
| Event listener | Receives and processes the event. |
The publisher does not need to know which listeners exist or what they do. You can add or remove listeners without modifying the publisher.
2. Main Spring event annotations and interfaces
| Annotation / Interface | Description |
|---|---|
ApplicationEvent |
Base class for traditional Spring events. |
ApplicationEventPublisher |
Publishes events. |
ApplicationListener<T> |
Interface for implementing event listeners. |
@EventListener |
Annotation-based event listener. |
@Async |
Executes a listener asynchronously. |
@EnableAsync |
Enables asynchronous method execution. |
@Order |
Defines listener invocation order. |
@TransactionalEventListener |
Executes a listener during a specific transaction phase. |
ApplicationEventMulticaster |
Responsible for distributing events to listeners. |
By default, Spring events are synchronous, in-process and non-persistent. They do not require a message broker such as Kafka or RabbitMQ.
3. Creating a simple custom event
Modern Spring applications can use ordinary Java classes or records as events. Extending ApplicationEvent is not mandatory.
Step 1: Create the event
UserRegisteredEvent.java
package com.example.demo.event;
public record UserRegisteredEvent(
Long userId,
String username,
String email
) {
}
A Java record is particularly suitable for an event because it provides an immutable data structure.
The event represents a fact that has already occurred: a user has registered.
Step 2: Create the event publisher
UserService.java
package com.example.demo.service;
import com.example.demo.event.UserRegisteredEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final ApplicationEventPublisher eventPublisher;
public UserService(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void registerUser(
Long userId,
String username,
String email) {
System.out.println("Registering user: " + username);
// Save the user in the database
UserRegisteredEvent event = new UserRegisteredEvent(
userId,
username,
email
);
eventPublisher.publishEvent(event);
System.out.println("Registration completed");
}
}
Spring automatically injects the ApplicationEventPublisher through constructor injection.
The following statement publishes the event to the application context:
eventPublisher.publishEvent(event);
Spring identifies the registered listeners that support this event type and invokes them.
Step 3: Create an event listener
EmailListener.java
package com.example.demo.listener;
import com.example.demo.event.UserRegisteredEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EmailListener {
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println(
"Sending welcome email to: " + event.email()
);
}
}
The @EventListener annotation tells Spring that this method should be executed whenever a compatible event is published.
Spring determines the event type from the method parameter.
Step 4: Create a REST controller
UserController.java
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/register")
public String registerUser(
@RequestBody RegisterUserRequest request) {
userService.registerUser(
1L,
request.username(),
request.email()
);
return "User registered successfully";
}
public record RegisterUserRequest(
String username,
String email
) {
}
}
Step 5: Test the application
Send the following HTTP request:
POST /api/users/register
Content-Type: application/json
{
"username": "john",
"email": "john@example.com"
}
Alternatively, use curl:
curl -X POST http://localhost:8080/api/users/register \
-H "Content-Type: application/json" \
-d '{"username":"john","email":"john@example.com"}'
Console output:
Registering user: john
Sending welcome email to: john@example.com
Registration completed
Notice that the email listener executes before the registration method completes. This happens because Spring events are synchronous by default.
This introductory example simulates database persistence and email delivery and uses a hardcoded user ID to demonstrate the event mechanism.
4. Multiple listeners for the same event
One of the main advantages of Spring events is that multiple listeners can subscribe to the same event.
In addition to the EmailListener, you can create the following listeners.
AuditListener.java
@Component
public class AuditListener {
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println(
"Creating audit log for user: " + event.userId()
);
}
}
AdminNotificationListener.java
@Component
public class AdminNotificationListener {
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println(
"Notifying administrator about: " + event.username()
);
}
}
The publisher remains unchanged:
eventPublisher.publishEvent(
new UserRegisteredEvent(userId, username, email)
);
All three listeners receive the event.
Possible output:
Registering user: john
Sending welcome email to: john@example.com
Creating audit log for user: 1
Notifying administrator about: john
Registration completed
Without explicitly configuring the listener order, you should not rely on a particular execution sequence.
5. Synchronous vs. asynchronous events
5.1. Synchronous events (default behavior)
By default, the publisher waits for ordinary synchronous listeners to finish.
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println(
Thread.currentThread().getName()
);
// Perform an operation
}
If an HTTP request publishes an event and the listeners take five seconds to complete, the HTTP request will also be delayed by approximately five seconds.
Synchronous execution
All operations execute sequentially on the calling thread.
Synchronous events are useful when the listener needs to participate in the publisher’s transaction or when the operation must complete before the publisher continues.
5.2. Asynchronous events using @Async
Asynchronous listeners allow the publisher to continue without waiting for the listener’s processing to finish.
First, enable asynchronous execution.
AsyncConfig.java
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncConfig {
}
Then modify the email listener.
EmailListener.java
import org.springframework.scheduling.annotation.Async;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EmailListener {
@Async
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println(
"Sending email to: " + event.email()
);
System.out.println(
"Thread: " + Thread.currentThread().getName()
);
}
}
The email listener now executes on a separate thread managed by a task executor.
Asynchronous execution
Example with both listeners configured as asynchronous and sufficient executor threads available.
Possible console output:
Registering user: john
Registration completed
Sending email to: john@example.com
Thread: task-1
The exact output order can vary because the threads execute independently.
5.3. Configuring a custom thread pool
For production applications, you can configure a dedicated executor for your event listeners.
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean("eventExecutor")
public Executor eventExecutor() {
ThreadPoolTaskExecutor executor =
new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("event-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);
executor.initialize();
return executor;
}
}
Specify the executor in the listener:
@Async("eventExecutor")
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println(
Thread.currentThread().getName()
);
}
| Configuration | Explanation |
|---|---|
corePoolSize |
Core number of worker threads. |
maxPoolSize |
Maximum number of worker threads. |
queueCapacity |
Maximum number of tasks waiting in the queue. |
threadNamePrefix |
Prefix used in worker thread names. |
waitForTasksToCompleteOnShutdown |
Allows queued and running tasks to complete during graceful shutdown. |
awaitTerminationSeconds |
Maximum time the container waits for executor termination. |
The pool initially grows toward five threads. Additional tasks are queued, and when the queue becomes full, the pool can grow toward twenty threads. If both limits are reached, new tasks can be rejected.
5.4. Synchronous vs. asynchronous comparison
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Annotation | @EventListener |
@Async + @EventListener |
| Execution thread | Publisher’s thread | Worker thread |
| Publisher waits | Yes | No, normally |
| Shares publisher transaction | Yes, if present | No |
| Listener exception propagated | Normally yes | No |
| Predictable execution order | With @Order |
Completion order not guaranteed |
| Suitable for slow operations | No | Yes |
| Persistent event storage | No | No |
Asynchronous listeners do not automatically inherit the publisher’s transaction or thread-local context.
Home+1
6. Controlling listener execution order with @Order
When multiple synchronous listeners receive the same event, you can control their invocation order using @Order.
import org.springframework.core.annotation.Order;
@Component
public class UserRegisteredListener {
@Order(1)
@EventListener
public void createAuditLog(UserRegisteredEvent event) {
System.out.println("1. Creating audit log");
}
@Order(2)
@EventListener
public void sendWelcomeEmail(UserRegisteredEvent event) {
System.out.println("2. Sending welcome email");
}
@Order(3)
@EventListener
public void notifyAdministrator(UserRegisteredEvent event) {
System.out.println("3. Notifying administrator");
}
}
Output:
1. Creating audit log
2. Sending welcome email
3. Notifying administrator
Lower values have higher priority.
Spring also provides the following constants:
@Order(Ordered.HIGHEST_PRECEDENCE)
@Order(Ordered.LOWEST_PRECEDENCE)
Important: When using asynchronous listeners, @Order does not guarantee that the asynchronous operations will finish in the specified order.
If one operation strictly depends on another operation completing, consider explicit service orchestration instead.
7. Conditional events using @EventListener(condition = ...)
Spring allows listeners to process events only when a specific condition is satisfied.
Conditions are written using Spring Expression Language (SpEL).
Step 1: Create an event
import java.math.BigDecimal;
public record OrderCreatedEvent(
Long orderId,
BigDecimal total,
String status
) {
}
Step 2: Create conditional listeners
@Component
public class OrderListener {
@EventListener(condition = "#a0.total().doubleValue() >= 1000")
public void handleLargeOrder(OrderCreatedEvent event) {
System.out.println(
"Large order received: " + event.orderId()
);
}
@EventListener(condition = "#a0.status() == 'PENDING'")
public void handlePendingOrder(OrderCreatedEvent event) {
System.out.println(
"Pending order: " + event.orderId()
);
}
@EventListener(condition = "#a0.status() == 'PAID'")
public void handlePaidOrder(OrderCreatedEvent event) {
System.out.println(
"Paid order: " + event.orderId()
);
}
}
Step 3: Publish the event
eventPublisher.publishEvent(
new OrderCreatedEvent(
100L,
new BigDecimal("1500.00"),
"PAID"
)
);
Output (in either order):
Large order received: 100
Paid order: 100
The pending-order listener is not executed.
Interactive example
Change the order amount and status to see which listeners will execute.
Order total
€1,500
€0
€1,000
€2,500
Order status
PendingPaidCancelled
handleLargeOrder()
total >= 1000
Executed
handlePendingOrder()
status == ‘PENDING’
Skipped
handlePaidOrder()
status == ‘PAID’
Executed
Simulated console output
Large order received: 100
Paid order: 100
#a0 refers to the first method argument. You can also use #event if Java parameter names are retained during compilation.
For production financial comparisons, prefer BigDecimal.compareTo() rather than converting monetary values to double.
8. Listening to multiple event types
A single listener can receive different types of events.
Define the events
public record UserRegisteredEvent(
Long userId,
String username,
String email
) {
}
public record UserDeletedEvent(
Long userId
) {
}
Create the listener
@Component
public class UserActivityListener {
@EventListener({
UserRegisteredEvent.class,
UserDeletedEvent.class
})
public void handleUserActivity(Object event) {
if (event instanceof UserRegisteredEvent registered) {
System.out.println(
"User registered: " + registered.userId()
);
} else if (event instanceof UserDeletedEvent deleted) {
System.out.println(
"User deleted: " + deleted.userId()
);
}
}
}
This listener receives both event types.
Alternatively, if you do not need the event data, you can omit the method parameter:
@EventListener({
UserRegisteredEvent.class,
UserDeletedEvent.class
})
public void invalidateUserCache() {
System.out.println("Invalidating user cache");
}
This is useful for cache invalidation, metrics collection and common operations shared by several events.
9. Publishing another event from a listener
A synchronous @EventListener method can return an object. Spring automatically publishes the returned object as another event.
Create a second event
public record WelcomeEmailSentEvent(
Long userId,
String email
) {
}
Create the first listener
@Component
public class EmailListener {
@EventListener
public WelcomeEmailSentEvent sendEmail(
UserRegisteredEvent event) {
System.out.println(
"Sending email to: " + event.email()
);
// Send the email successfully
return new WelcomeEmailSentEvent(
event.userId(),
event.email()
);
}
}
Create the second listener
@Component
public class EmailAuditListener {
@EventListener
public void handleEmailSent(WelcomeEmailSentEvent event) {
System.out.println(
"Email successfully sent to: " + event.email()
);
}
}
Spring can also publish multiple events when a synchronous listener returns an array or collection of events.
Publishing from an asynchronous listener
Returning an event does not work with an asynchronous listener. Instead, inject ApplicationEventPublisher and publish it explicitly.
Home
@Component
public class EmailListener {
private final ApplicationEventPublisher publisher;
public EmailListener(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@Async
@EventListener
public void sendEmail(UserRegisteredEvent event) {
// Send the email successfully
publisher.publishEvent(
new WelcomeEmailSentEvent(
event.userId(),
event.email()
)
);
}
}
Be careful not to create circular event chains where two listeners continuously publish events that trigger each other.
10. Traditional events using ApplicationEvent and ApplicationListener
Before annotation-based event listeners were introduced, Spring applications typically extended ApplicationEvent and implemented ApplicationListener.
This approach is still supported.
Step 1: Extend ApplicationEvent
import org.springframework.context.ApplicationEvent;
public class UserCreatedEvent extends ApplicationEvent {
private final Long userId;
private final String email;
public UserCreatedEvent(
Object source,
Long userId,
String email) {
super(source);
this.userId = userId;
this.email = email;
}
public Long getUserId() {
return userId;
}
public String getEmail() {
return email;
}
}
The source represents the object responsible for creating the event.
The parent class also provides methods such as:
event.getSource();
event.getTimestamp();
Step 2: Implement ApplicationListener
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class UserCreatedListener
implements ApplicationListener<UserCreatedEvent> {
@Override
public void onApplicationEvent(UserCreatedEvent event) {
System.out.println(
"User created: " + event.getUserId()
);
System.out.println(
"Email: " + event.getEmail()
);
}
}
Step 3: Publish the event
eventPublisher.publishEvent(
new UserCreatedEvent(
this,
1L,
"john@example.com"
)
);
Which approach should you use?
| Feature | Traditional approach | Modern approach |
|---|---|---|
| Event definition | Extends ApplicationEvent |
Java class or record |
| Listener definition | Implements ApplicationListener |
@EventListener |
| Boilerplate | More | Less |
| Source and timestamp | Built into event class | Define if required |
| Conditional listeners | Manual conditions | SpEL support |
| Multiple listener methods per class | Less convenient | Yes |
| Recommended for new custom events | Usually no | Yes |
For new Spring Boot applications, I recommend Java records combined with @EventListener.
11. Transactional events using @TransactionalEventListener
This is one of the most important features when working with Spring Boot, Spring Data JPA and database transactions.
Consider the following service:
@Service
public class UserService {
private final UserRepository userRepository;
private final ApplicationEventPublisher publisher;
public UserService(
UserRepository userRepository,
ApplicationEventPublisher publisher) {
this.userRepository = userRepository;
this.publisher = publisher;
}
@Transactional
public User registerUser(String username, String email) {
User user = new User();
user.setUsername(username);
user.setEmail(email);
userRepository.save(user);
publisher.publishEvent(
new UserRegisteredEvent(
user.getId(),
user.getUsername(),
user.getEmail()
)
);
return user;
}
}
11.1. The problem with ordinary @EventListener
Suppose you have this listener:
@EventListener
public void sendWelcomeEmail(UserRegisteredEvent event) {
System.out.println("Sending welcome email");
// Send email
}
The listener executes before the database transaction has necessarily committed.
If the transaction subsequently fails, the user might receive a welcome email even though their account was never successfully created.
Ordinary event listener
The email was sent, but the user does not exist in the database.
11.2. The solution: @TransactionalEventListener
import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.transaction.event.TransactionPhase;
@Component
public class EmailListener {
@TransactionalEventListener(
phase = TransactionPhase.AFTER_COMMIT
)
public void sendWelcomeEmail(UserRegisteredEvent event) {
System.out.println(
"Sending welcome email to: " + event.email()
);
// Send email
}
}
The listener executes only after the transaction commits successfully.
Transactional event listener
AFTER_COMMIT is the default phase, so the following is equivalent:
@TransactionalEventListener
public void sendWelcomeEmail(UserRegisteredEvent event) {
// Send email
}
11.3. All transaction phases
Spring provides four transaction phases.
Home
| Transaction phase | When the listener executes |
|---|---|
BEFORE_COMMIT |
Before the transaction commits. |
AFTER_COMMIT |
After a successful commit. Default behavior. |
AFTER_ROLLBACK |
After a rollback. |
AFTER_COMPLETION |
After either a commit or a rollback. |
Transaction lifecycle
Simplified lifecycle. A transaction can still fail after BEFORE_COMMIT executes.
11.4. BEFORE_COMMIT
@TransactionalEventListener(
phase = TransactionPhase.BEFORE_COMMIT
)
public void beforeCommit(UserRegisteredEvent event) {
System.out.println(
"Preparing to commit user: " + event.userId()
);
}
Useful for operations that must participate in the existing transaction, such as additional database updates.
An exception thrown here can prevent the transaction from committing.
11.5. AFTER_COMMIT
@TransactionalEventListener(
phase = TransactionPhase.AFTER_COMMIT
)
public void afterCommit(UserRegisteredEvent event) {
System.out.println("User successfully saved");
// Send notification
}
Useful for sending notifications, invalidating caches, updating a search index or triggering external API calls after successful database persistence.
11.6. AFTER_ROLLBACK
@TransactionalEventListener(
phase = TransactionPhase.AFTER_ROLLBACK
)
public void afterRollback(UserRegisteredEvent event) {
System.out.println(
"Registration rolled back for: " + event.username()
);
}
Useful for recording failed operations, cleanup or triggering compensating actions.
11.7. AFTER_COMPLETION
@TransactionalEventListener(
phase = TransactionPhase.AFTER_COMPLETION
)
public void afterCompletion(UserRegisteredEvent event) {
System.out.println(
"Registration transaction completed"
);
}
Executes regardless of whether the transaction succeeded or failed.
11.8. What happens when there is no transaction?
Consider this method without @Transactional:
public void registerUser() {
publisher.publishEvent(
new UserRegisteredEvent(
1L,
"john",
"john@example.com"
)
);
}
If there is no active transaction, the transactional listener will not execute by default.
You can override this behavior:
@TransactionalEventListener(
phase = TransactionPhase.AFTER_COMMIT,
fallbackExecution = true
)
public void handleUserRegistered(UserRegisteredEvent event) {
System.out.println("Processing event");
}
| Situation | fallbackExecution = false |
fallbackExecution = true |
|---|---|---|
| Active transaction commits | Executes after commit | Executes after commit |
| Active transaction rolls back | Skipped | Skipped |
| No active transaction | Skipped | Executes immediately |
This table assumes the AFTER_COMMIT phase.
12. Performing database operations inside transactional listeners
A common mistake is performing database writes inside an AFTER_COMMIT listener without starting a new transaction.
@TransactionalEventListener
public void handleUserRegistered(UserRegisteredEvent event) {
auditRepository.save(
new AuditLog("User registered")
);
}
The original transaction has already committed. Although some transaction resources may still be accessible, additional changes are not guaranteed to be committed as intended.
The recommended approach is to create a separate transactional service.
AuditService.java
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AuditService {
private final AuditRepository auditRepository;
public AuditService(AuditRepository auditRepository) {
this.auditRepository = auditRepository;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void createAuditLog(Long userId) {
AuditLog log = new AuditLog();
log.setMessage("User registered: " + userId);
auditRepository.save(log);
}
}
AuditListener.java
@Component
public class AuditListener {
private final AuditService auditService;
public AuditListener(AuditService auditService) {
this.auditService = auditService;
}
@TransactionalEventListener
public void handleUserRegistered(UserRegisteredEvent event) {
auditService.createAuditLog(event.userId());
}
}
The audit operation now has its own independent transaction.
If the second transaction fails, it cannot roll back the already committed first transaction.
13. Combining @Async with @TransactionalEventListener
You can combine both annotations to process an event asynchronously, but only after a successful database commit.
@Component
public class EmailListener {
@Async("eventExecutor")
@TransactionalEventListener(
phase = TransactionPhase.AFTER_COMMIT
)
public void sendWelcomeEmail(UserRegisteredEvent event) {
System.out.println(
"Sending welcome email to: " + event.email()
);
// Perform potentially slow email operation
}
}
This is particularly useful in REST API applications.
Benefits include:
- The email is not sent if the database transaction fails.
- The HTTP request does not need to wait for email delivery.
- Slow external operations do not unnecessarily extend the original database transaction.
- The email listener remains independent of the user registration service.
However, this does not guarantee delivery. If the application crashes after committing the transaction but before executing the asynchronous task, the event may be lost.
14. Exception handling in event listeners
14.1. Synchronous listener exceptions
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
throw new IllegalStateException("Email service unavailable");
}
With the default event configuration, the exception propagates back to the publisher.
publisher.publishEvent(event);
// May never be reached
System.out.println("Event published successfully");
If the publisher is executing inside a transaction, an unhandled runtime exception can cause the transaction to roll back. Other listeners that have not yet executed may also be skipped.
14.2. Asynchronous listener exceptions
@Async
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
throw new IllegalStateException("Email service unavailable");
}
The exception occurs on the worker thread and does not propagate back to the publisher.
You can configure a global handler for exceptions thrown by asynchronous void methods.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
private static final Logger log =
LoggerFactory.getLogger(AsyncConfig.class);
@Override
public AsyncUncaughtExceptionHandler
getAsyncUncaughtExceptionHandler() {
return (exception, method, params) -> {
log.error(
"Async operation failed: " + method.getName(),
exception
);
};
}
}
You can merge this configuration with the custom executor configuration from section 5.
This handler logs failures, but it does not automatically retry failed operations.
14.3. Handling exceptions locally
You can also handle exceptions directly inside the listener:
@Async
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
try {
emailService.sendWelcomeEmail(event.email());
} catch (Exception exception) {
log.error(
"Failed to send welcome email for user {}",
event.userId(),
exception
);
// Record failure or schedule a retry
}
}
For important operations, consider persistent failure tracking, retry policies and idempotent processing.
15. Built-in Spring Boot events
Spring Boot automatically publishes several events during application startup, operation and shutdown.
You do not need to publish these events yourself.
15.1. Application lifecycle events
-
ApplicationStartingEvent
Application startup begins.
-
ApplicationEnvironmentPreparedEvent
Configuration properties and environment are available.
-
ApplicationContextInitializedEvent
The application context is prepared.
-
ApplicationPreparedEvent
Bean definitions are loaded, before context refresh.
-
ContextRefreshedEvent
The application context has been refreshed.
-
ApplicationStartedEvent
The context is ready, but application runners have not yet executed.
-
ApplicationRunner / CommandLineRunner
Startup runner methods execute. This is a lifecycle step, not an event.
-
ApplicationReadyEvent
Startup processing is complete.
Other important built-in events include:
| Event | Description |
|---|---|
ApplicationFailedEvent |
Application startup failed. |
ContextClosedEvent |
Application context is closing. |
ContextStartedEvent |
Application context was explicitly started. |
ContextStoppedEvent |
Application context was explicitly stopped. |
WebServerInitializedEvent |
Embedded web server was initialized. |
AvailabilityChangeEvent |
Application liveness or readiness changed. |
15.2. ApplicationReadyEvent
This is useful when you want to perform an operation once application startup has completed.
import org.springframework.boot.context.event.ApplicationReadyEvent;
@Component
public class ApplicationStartupListener {
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
System.out.println(
"Spring Boot application is ready"
);
}
}
Typical use cases include lightweight startup notifications, initializing application-specific monitoring and triggering background tasks.
15.3. ApplicationStartedEvent
import org.springframework.boot.context.event.ApplicationStartedEvent;
@Component
public class ApplicationStartedListener {
@EventListener
public void onApplicationStarted(
ApplicationStartedEvent event) {
System.out.println("Application context started");
}
}
The difference is that ApplicationStartedEvent occurs before the execution of application runners, whereas ApplicationReadyEvent occurs afterward.
15.4. ContextClosedEvent
import org.springframework.context.event.ContextClosedEvent;
@Component
public class ShutdownListener {
@EventListener
public void onApplicationShutdown(ContextClosedEvent event) {
System.out.println("Application is shutting down");
// Perform lightweight cleanup
}
}
Useful for releasing application-specific resources during graceful shutdown.
15.5. WebServerInitializedEvent
import org.springframework.boot.web.context.WebServerInitializedEvent;
@Component
public class WebServerListener {
@EventListener
public void onWebServerInitialized(
WebServerInitializedEvent event) {
int port = event.getWebServer().getPort();
System.out.println(
"Web server started on port: " + port
);
}
}
This is particularly useful when the application uses a dynamically assigned port:
server.port=0
15.6. Listening to early startup events
Some events occur before Spring has initialized its application context. Consequently, registering an ordinary @Component listener is insufficient for those events.
Instead, register the listener programmatically.
Home
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;
public class StartingListener
implements ApplicationListener<ApplicationStartingEvent> {
@Override
public void onApplicationEvent(
ApplicationStartingEvent event) {
System.out.println("Application is starting");
}
}
Register it in the main application class:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication application =
new SpringApplication(DemoApplication.class);
application.addListeners(new StartingListener());
application.run(args);
}
}
16. Spring Security events
If your application uses Spring Security, you can also listen to authentication and authorization events.
Successful authentication
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
@Component
public class AuthenticationListener {
@EventListener
public void onAuthenticationSuccess(
AuthenticationSuccessEvent event) {
String username =
event.getAuthentication().getName();
System.out.println(
"Successful authentication: " + username
);
}
}
Failed authentication
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
@Component
public class AuthenticationFailureListener {
@EventListener
public void onAuthenticationFailure(
AuthenticationFailureBadCredentialsEvent event) {
String username =
event.getAuthentication().getName();
System.out.println(
"Failed authentication: " + username
);
}
}
If your authentication configuration does not already provide an authentication event publisher, you can register one:
@Bean
public AuthenticationEventPublisher authenticationEventPublisher(
ApplicationEventPublisher publisher) {
return new DefaultAuthenticationEventPublisher(publisher);
}
Required imports:
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
These events are useful for security audit logs, monitoring authentication failures and detecting suspicious login activity.
Avoid including passwords, access tokens or other credentials in your event logs.
17. Testing Spring Boot events
Spring provides built-in support for recording events published during integration tests.
17.1. Testing whether an event was published
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.RecordApplicationEvents;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@RecordApplicationEvents
class UserServiceTest {
@Autowired
private UserService userService;
@Autowired
private ApplicationEvents applicationEvents;
@Test
void shouldPublishUserRegisteredEvent() {
userService.registerUser(
1L,
"john",
"john@example.com"
);
assertThat(
applicationEvents.stream(UserRegisteredEvent.class)
)
.hasSize(1)
.anySatisfy(event -> {
assertThat(event.userId()).isEqualTo(1L);
assertThat(event.email())
.isEqualTo("john@example.com");
});
}
}
This example uses the introductory UserService from section 3.
@RecordApplicationEvents records application events published during the test, while ApplicationEvents allows you to inspect them.
17.2. Unit testing a listener
A listener can also be tested as an ordinary Java class without starting the Spring application.
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
class EmailListenerTest {
@Test
void shouldSendWelcomeEmail() {
EmailService emailService = mock(EmailService.class);
EmailListener listener =
new EmailListener(emailService);
UserRegisteredEvent event =
new UserRegisteredEvent(
1L,
"john",
"john@example.com"
);
listener.handleUserRegistered(event);
verify(emailService)
.sendWelcomeEmail("john@example.com");
}
}
This assumes the following listener implementation:
@Component
public class EmailListener {
private final EmailService emailService;
public EmailListener(EmailService emailService) {
this.emailService = emailService;
}
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
emailService.sendWelcomeEmail(event.email());
}
}
This tests the listener’s business logic but not Spring’s event dispatch mechanism.
17.3. Testing transactional event listeners
Spring integration tests annotated with @Transactional normally roll back at the end of the test.
This means an AFTER_COMMIT listener may never execute.
You can explicitly commit the test transaction:
import org.springframework.test.context.transaction.TestTransaction;
@SpringBootTest
@Transactional
class TransactionalEventTest {
@Autowired
private UserService userService;
@Test
void shouldExecuteListenerAfterCommit() {
userService.registerUser(
"john",
"john@example.com"
);
TestTransaction.flagForCommit();
TestTransaction.end();
// Verify that the AFTER_COMMIT listener executed
}
}
This example uses the JPA-based UserService from section 11.
For asynchronous listeners, use an eventual assertion mechanism such as Awaitility rather than relying on Thread.sleep().
Remember that explicitly committing a test transaction persists its database changes, so arrange appropriate test-data cleanup.
18. Recommended project directory structure
For a medium-sized Spring Boot REST API application, you could organize your events as follows:
com.example.demo
config
AsyncConfig.java
controller
UserController.java
entity
User.java
AuditLog.java
repository
UserRepository.java
AuditRepository.java
service
UserService.java
EmailService.java
AuditService.java
event
UserRegisteredEvent.java
UserDeletedEvent.java
WelcomeEmailSentEvent.java
listener
EmailListener.java
AuditListener.java
AdminNotificationListener.java
DemoApplication.java
For larger applications, I recommend organizing packages by business feature rather than by technical layer.
com.example.demo
├── config
│ └── AsyncConfig.java
├── user
│ ├── User.java
│ ├── UserController.java
│ ├── UserRepository.java
│ ├── UserService.java
│ └── event
│ ├── UserRegisteredEvent.java
│ └── UserDeletedEvent.java
├── notification
│ ├── EmailService.java
│ └── listener
│ └── UserRegisteredListener.java
├── audit
│ ├── AuditService.java
│ └── listener
│ └── UserAuditListener.java
└── DemoApplication.java
This keeps related functionality together and makes it easier to transition toward a modular monolith architecture.
19. Spring Boot events vs. Kafka and RabbitMQ
Spring events are not a replacement for a message broker in distributed applications.
Spring events
Communication inside one application instance.
Message broker
Communication between independent application instances.
| Feature | Spring events | Kafka | RabbitMQ |
|---|---|---|---|
| Communication | In-process | Distributed | Distributed |
| External infrastructure | No | Yes | Yes |
| Persistent messages | No | Yes | Configurable |
| Message replay | No | Yes | Limited or stream-based |
| Independent applications | No | Yes | Yes |
| Automatic delivery recovery | No | Supported | Supported |
| Configuration complexity | Low | Higher | Higher |
| Typical use | Internal application events | Event streaming | Message queues and routing |
When Spring events are not sufficient
Suppose an application saves an entity to MySQL and then publishes an event to update a Solr search index.
@Async
@TransactionalEventListener
public void updateSearchIndex(DocumentUpdatedEvent event) {
solrService.indexDocument(event.documentId());
}
This is convenient, but if the application crashes after the MySQL transaction commits and before Solr indexing completes, the search index may become inconsistent with the database.
For operations that require reliable delivery, consider the Transactional Outbox pattern.
The event is saved in an outbox database table in the same transaction as the business entity. A background process reads pending events, processes them and retries failures.
You can also consider Spring Modulith, which provides additional support for modular Spring applications and persistent event publication tracking.
20. Best practices for Spring Boot events
Use immutable events
Prefer:
public record UserRegisteredEvent(
Long userId,
String email
) {
}
Instead of mutable event classes with setters.
Records are shallowly immutable, so be careful when including mutable collections or other mutable objects.
Avoid passing JPA entities in events
Not recommended:
public record UserRegisteredEvent(User user) {
}
Recommended:
public record UserRegisteredEvent(
Long userId,
String email
) {
}
Passing JPA entities to asynchronous listeners can cause problems with lazy-loaded relationships, detached entities, persistence contexts and thread safety.
Pass IDs and the required data instead.
Use meaningful event names
Events should generally describe something that happened.
| Recommended | Less descriptive |
|---|---|
UserRegisteredEvent |
UserEvent |
OrderPaidEvent |
ProcessOrderEvent |
DocumentIndexedEvent |
IndexEvent |
PasswordChangedEvent |
PasswordEvent |
ArchiveCreatedEvent |
ArchiveActionEvent |
Keep event listeners focused
Instead of creating one listener that sends emails, writes audit logs, updates caches and notifies administrators, create independent listeners for each responsibility.
Make listeners idempotent when necessary
If an event is retried or processed more than once, it should not produce unintended duplicate side effects.
For example, you can include a unique event identifier:
import java.time.Instant;
import java.util.UUID;
public record UserRegisteredEvent(
UUID eventId,
Long userId,
String email,
Instant occurredAt
) {
}
Publish the event:
publisher.publishEvent(
new UserRegisteredEvent(
UUID.randomUUID(),
user.getId(),
user.getEmail(),
Instant.now()
)
);
A persistent processed-event registry can help prevent duplicate database operations when implemented transactionally. External operations may also require their own idempotency mechanisms.
Do not overuse events
If a service requires another operation to return a result before it can continue, a direct method call is often clearer.
PaymentResult result = paymentService.processPayment(order);
Events are more appropriate for independent reactions to a completed business operation.
publisher.publishEvent(
new OrderPaidEvent(order.getId())
);
21. Which event listener should you use?
| Use case | Recommended approach |
|---|---|
| Simple communication between components | @EventListener |
| Sending non-critical emails in the background | @Async + @EventListener |
| Sending emails after successful database persistence | @Async + @TransactionalEventListener |
| Updating data within the same transaction | @EventListener or BEFORE_COMMIT |
| Updating data in a separate transaction | AFTER_COMMIT + REQUIRES_NEW |
| Handling transaction failures | AFTER_ROLLBACK |
| Cache invalidation after database changes | AFTER_COMMIT |
| Executing listeners in a specific order | @Order |
| Processing only matching events | @EventListener(condition = ...) |
| Performing startup operations | ApplicationReadyEvent |
| Performing shutdown cleanup | ContextClosedEvent |
| Reliable MySQL-to-Solr synchronization | Transactional Outbox or persistent event publication |
| Communication between microservices | Kafka or RabbitMQ |
22. Recommended implementation for Spring Boot REST APIs
For a typical Spring Boot REST API using Spring Data JPA, I recommend the following combination.
Event:
public record UserRegisteredEvent(
Long userId,
String email
) {
}
Publisher:
@Transactional
public User registerUser(User user) {
User savedUser = userRepository.save(user);
eventPublisher.publishEvent(
new UserRegisteredEvent(
savedUser.getId(),
savedUser.getEmail()
)
);
return savedUser;
}
Listener:
@Async("eventExecutor")
@TransactionalEventListener(
phase = TransactionPhase.AFTER_COMMIT
)
public void handleUserRegistered(UserRegisteredEvent event) {
emailService.sendWelcomeEmail(event.email());
}
Configuration:
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean("eventExecutor")
public Executor eventExecutor() {
ThreadPoolTaskExecutor executor =
new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("event-");
executor.initialize();
return executor;
}
}
This combination provides loose coupling, transaction-aware execution and asynchronous processing without requiring additional infrastructure.
The main limitation is that events remain in memory. For critical operations where losing an event is unacceptable, use persistent event publication or the Transactional Outbox pattern instead.
The examples in this guide use modern Java records and conventional Spring Boot APIs suitable for Spring Boot 3.x and 4.x applications. They are illustrative snippets rather than a single compiled project; repository definitions, entity mappings, actual email delivery and some routine imports have been omitted.