1. Overview
- In the Spring framework, @EventListener is an annotation for handling application events. It provides a convenient way to listen and respond to various events, so that the code can be structured based on an event-driven way. Through the @EventListener annotation, a method can be marked as an event listener. When the corresponding event is published, the method will be automatically called.
2. Event-driven architecture basics
- Event: Events are abstract representations of an action or state change in the application. For example, user registration is successful, order is paid, file upload is completed, etc. can all be regarded as events. In Spring, events are usually a class inherited from ApplicationEvent.
- Publisher: The component responsible for publishing events. It creates and publishes events during the execution of a specific business logic. For example, in the user registration service class, when the user registration is successful, a UserRegisteredEvent will be published.
- Event Listener: The class where the method annotated tagged through @EventListener is the event listener. It will subscribe to events of interest. When the event is published, the corresponding methods in the listener will be triggered to execute custom logic, such as sending welcome emails, updating user points, etc.
3. Use examples
- Defining event class: First, you need to define an event class, inherit from ApplicationEvent. For example, define an event class where a user registration is successful:
- Here, the UserRegisteredEvent class inherits from ApplicationEvent and contains a User object to pass user-related information.
- Publish event: In business logic, when the user registers successfully, publish an event. Suppose there is a user registration method in a UserService class:
import ; import ; @Service public class UserService { private final ApplicationEventPublisher eventPublisher; public UserService(ApplicationEventPublisher eventPublisher) { = eventPublisher; } public void registerUser(User user) { // Actual user registration logic, such as saving user information to the database, etc. //... // Publish events after successful registration UserRegisteredEvent event = new UserRegisteredEvent(this, user); (event); } }
- Here, the UserService class injects ApplicationEventPublisher through the constructor. After the user registration is successful, the UserRegisteredEvent is created and published.
- Listen to events: Use the @EventListener annotation to listen for events. For example, create a listener class to send a welcome email to a newly registered user:
import ; import ; @Component public class WelcomeEmailListener { @EventListener public void sendWelcomeEmail(UserRegisteredEvent event) { User user = (); // The logic of sending welcome emails, such as calling the email sending service ("Send a welcome email to the user: " + ()); } }
- In this WelcomeEmailListener class, the sendWelcomeEmail method uses the @EventListener annotation mark. When the UserRegisteredEvent event is published, the method will be called, thereby realizing the logic of sending welcome emails.
4. Flexibility and configuration of event listeners
- Listen to multiple events: A @EventListener annotation method can listen for multiple events. The event to be listened to can be specified by the type of method parameters. For example:
import ; import ; @Component public class MultipleEventListener { @EventListener public void handleEvents(UserRegisteredEvent userEvent, OrderPlacedEvent orderEvent) { if (userEvent!= null) { ("Processing user registration events"); // Logic related to user registration event } if (orderEvent!= null) { ("Processing order placement events"); // Related logic for order placement events } } }
- In this example, the handleEvents method can listen to both UserRegisteredEvent and OrderPlacedEvent events, distinguish which event is based on the passed parameter type, and execute the corresponding logic.
- Asynchronous listening to events: The event listener can be configured to execute asynchronously to improve application performance and response speed. In Spring Boot, asynchronous support can be enabled through the @EnableAsync annotation, and then the async = true attribute is added to the @EventListener annotation. For example:
import ; import ; @Configuration @EnableAsync public class AsyncConfig { //Configuration class content}
- Then in the listener method:
import ; import ; import ; @Component public class AsyncEventListener { @Async @EventListener public void handleAsyncEvent(UserRegisteredEvent event) { // Asynchronous execution logic, such as sending SMS notifications, will not block the main thread ("Asynchronously handle user registration events"); } }
Built-in listener
- Built-in listeners in Spring for example: ApplicationReadyEvent listener, ApplicationStartedEvent listener, ServletWebServerInitializedEvent listener, etc. These listeners can be implemented by the ApplicationListenner<> Generic Interface The generic parameters must be the ApplicationEvent itself or a subclass.
- In this example, the ApplicationReadyEvent listener is implemented, which is a very important event in Spring Boot. It fires after the Spring application is fully ready to receive the request, which means that all Spring beans have been initialized, the configuration file has been loaded, and the application context has been completely refreshed.
import ; import ; import ; @Component public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> { @Override public void onApplicationEvent(ApplicationReadyEvent event) { ("The application is ready and can start receiving requests!"); // Here you can perform database connection checks, cache warm-ups and other operations // For example, some redis caches are loaded here. Something... } }
This is all about this article about the implementation of SpringBoot event listener @EventListener. For more related SpringBoot @EventListener content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!