An eventing mechanism is a powerful tool for decoupling different components of application modules. Application level events are also useful for maintaining state changes in an application. In this article, we will create a simple application to Spring framework based eventing mechanism to publish events and listening to the events. This article presumes the working maven installation.
Let’s start by creating a simple maven project “spring-app-event-demo” by executing the following command on your terminal application:
Spring eventing framework works on the Base Object ApplicationEvent. Now, create an interface “IAppEventPublisher” to publish your event.
Now we will implement IAppEventPublisher to publish our demo events. Spring has interface ApplicationEventPublisher to publish the events and ApplicationEventPublisherAware to make the spring bean aware of eventing framework. Create a class AppEventPublisher which implements interfaces ApplicationEventPublisherAware and IAppEventPublisher as:
You may have noticed above, I have added annotation @Component to create class AppEventPublisher as a spring bean.
Before creating our event listener, first, create a model class NewAppEvent for our application event.
For creating the Application event listener, you need to implement ApplicationListener<E extends ApplicationEvent>. Create a listener AppEventListener, which will log any event it receives.
You are almost done with your basic spring application eventing framework. Now you need to configure all the spring beans. Let us create a java class AppConfiguration to specify spring configuration:
You can download the complete source code from my git repository.