Spring Framework FAQ: Top Questions
42. How does Spring manage application events?
Spring provides a flexible eventing system to publish and listen to application-level events, using ApplicationEventPublisher
and @EventListener
.
📘 Steps:
- Define a custom event class.
- Publish the event using
ApplicationEventPublisher
. - Handle it using
@EventListener
.
📥 Example:
public class UserRegisteredEvent extends ApplicationEvent {
public UserRegisteredEvent(Object source) {
super(source);
}
}
@Component
public class UserListener {
@EventListener
public void onUserRegister(UserRegisteredEvent event) {
System.out.println("User registered!");
}
}
🏆 Expected Output:
Prints "User registered!" when the event is triggered.
🛠️ Use Cases:
- Triggering async operations post entity actions.
- Implementing decoupled workflows or notifications.