Spring Custom Event Handling

In this article, we will learn about Spring Custom Event Handling with examples, Spring Framework one of the most mature Java web frameworks.

Application Event handling is another way to achieve the loose coupling in the Spring. Using Events, an Event publisher object can communicate with other objects without even knowing which object is listen.

Spring allows us to create listeners in the code. We can create beans that listen for events which are published through our ApplicationContext. Spring ApplicationContext is capable to behave like an event bus which enables simple communication between Spring beans within the same ApplicationContext.

In spring event-based communication model, the sender component just publishes an event without knowing who the receiver will be. There might be more than one receiver component.

Also, the receiver needn’t know who is publishing the event. The listener can listen to multiple events from different senders at the same time. In this way, the sender and receiver components are loosely coupled.

There are a few simple guidelines to follow:

  • The event should extend ApplicationEvent
  • The publisher should inject an ApplicationEventPublisher object
  • The listener should implement the ApplicationListgitener interface

Spring Custom Event Handling example:

Step 1 :

Create an event class, NotificationEvent by extending ApplicationEvent. This class must define a default constructor, which should inherit constructor from ApplicationEvent class.

File: NotificationEvent.java

Step 2 :

Once your event class is defined, you can publish it from any class, let us say NotificationPublisher which implements ApplicationEventPublisherAware.

You will also need to declare this class in XML configuration file as a bean so that the container can identify the bean as an event publisher because it implements the ApplicationEventPublisherAware interface.

File: NotificationPublisher.java

Step 3 :

A published event can be handled in a class, let us say NotificationEventListener which implements ApplicationListener interface and implements onApplicationEvent method for the custom event.

File: NotificationEventListener.java

Step 4: Spring Configuration

File: Beans.xml

Step 5 :

The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

File: App.java

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons