An event in Spring is a class that extends ApplicationEvent class, published by a class that implements ApplicationEventPublisherAware, and handled by a class that implements ApplicationListener interface.
The ApplicationContext manages the complete life cycle of the beans. Sounds familiar, Isn’t it?.
In Spring, we have a set of pre-defined events that get published by the ApplicationContext during life cycle of the context.
For example, a ContextStartedEvent is published when the context is started and ContextStoppedEvent is published when the context is stopped.
💡This is useful so we can hook into the life cycle of the context and add in our own custom logic.
So, If a class implements the ApplicationListener, then every time an event gets published by the ApplicationContext, that class is notified.
💡Spring’s event are synchronous (single-threaded). So, if an event is published, until and unless all the receivers get the message, the processes are blocked and the flow will not continue.
Listening To ApplicationContext Events 🎧
To listen to a context event, a class (listener) should implement the ApplicationListener interface and override the
💡You also need to declare this class as a bean (i.e. In XML configuration file) so that the container can identify the bean as an event listener, thus will be notified.
<bean id="contextStartEventHandler" class="ContextStartEventHandler"></bean>
Instead, you can write, publish and handle your own custom Spring events. All what you need to do is as the following:
- Create the event, and extend ApplicationEvent class.
- Create the publisher, and implement ApplicationEventPublisher (or ApplicationEventPublisherAware).
- Create the listener, and implement ApplicationListener.
The event class is to store the event data. Let’s create a simple event class.
The publisher constructs the event object and publishes it to anyone who’s listening.
To publish an event, either:
 Inject the ApplicationEventPublisher object using
 The publisher class can implement the ApplicationEventPublisherAware interface, and the
setApplicationEventPublisher() method which sets the ApplicationEventPublisher object.
⚠ In case of publisher implements the ApplicationEventPublisherAware interface. The publisher class has to be declared as a bean so that the container can identify the bean as an event publisher.
<bean id="customEventPublisher" class="CustomEventPublisher"/>
The listener fires whenever the event gets published.
It implements ApplicationListener interface and has to be defined as a bean (as we did before).
Putting All Together
Let’s test our custom event.
Thank you for reading! If you enjoyed it, please clap 👏 for it.