Spring Framework FAQ: Top Questions
17. How does Spring handle events and listeners?
Spring has a built-in event publishing mechanism that follows the Observer pattern. Beans can publish and listen to custom or predefined events.
πΊοΈ Components:
ApplicationEventPublisher
to publish events.@EventListener
orApplicationListener
to listen for them.
π₯ Example:
public class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
@Component
public class MyListener {
@EventListener
public void handleEvent(MyEvent event) {
System.out.println("Handled event: " + event);
}
}
π Expected Output:
Custom event is published and handled by listener bean.
π οΈ Use Cases:
- Decoupling components via event communication.
- Triggering background or audit logic upon domain events.