In Spring Framework, the @EventListener annotation is used to handle and respond to events that occur within an application. It allows you to define methods that will be executed when specific events are published in the Spring application context. These events can be either standard events provided by Spring or custom events that you create.
Here’s how you can use the @EventListener annotation in Spring:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class UserRegisteredEvent extends ApplicationEvent {
private User user;
public UserRegisteredEvent(User user) {
super(user);
this.user = user;
}
public User getUser() {
return user;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class UserService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void registerUser(User user) {
// Perform user registration logic
// ...
// Publish the UserRegisteredEvent
UserRegisteredEvent event = new UserRegisteredEvent(user);
eventPublisher.publishEvent(event);
}
}
1
2
3
4
5
6
7
8
9
10
11
@Component
public class UserRegisteredEventListener {
@EventListener
public void handleUserRegisteredEvent(UserRegisteredEvent event) {
User user = event.getUser();
// Perform actions upon user registration
// ...
}
}
In the above example, the handleUserRegisteredEvent method is annotated with @EventListener and takes the UserRegisteredEvent as a parameter. Whenever a UserRegisteredEvent is published, this method will be invoked and can perform specific actions based on the event data.
Note that you can have multiple event listeners for the same event, and all of them will be invoked when the event is published.
By using the @EventListener annotation, you can decouple components in your application and respond to events in a loosely coupled manner. It promotes the separation of concerns and allows you to handle application events without explicitly wiring and invoking event handlers.