Skip to main content

Spring 4.3 – Event Listener

Spring logo

1) Overview

In this tutorial, we are going to discuss how to handle events in Spring Framework. We are using Spring Framework 4.3. Firstly, we need to setup plain REST service using the Spring Boot. Then, we will go through the event handling.

Building a simple REST Service with Spring Boot

2) Spring REST service with Spring Boot

Now, these are the basic steps to implement simple REST service using spring-boot. In this example, we were using a Gradle as a build tool. First of all, add the spring-boot dependency into the project (build.gradle).

Then create a domain model that name is User.java in com.mydevgeek.domain package.

Create an Application.java in com.mydevgeek.app package. This is working as the main class.

3) Event Listener

The Event listener responsibility is when trigger some event do some operation. There 2 ways to define the event listener in the Spring framework.

  1. Using Generic
  2. Using Annotation

3.1) Using Generic

Create a package com.mydevgeek.event. Inside this package create a UserEvent.java and extends the org.springframework.context.ApplicationEvent.

Now, we are going to create the Event Listener. Create a class that name is UserEventListener.java and implements org.springframework.context.ApplicationListener.

3.2) Using Annotation

If you using the annotation, you need to modify the UserEventListener.java. We can use the @EventListener annotation instead of implementing the ApplicationListener.

Note: – in this case, we can use any name for the method.

4) Event Publisher

We need to simple REST Controller to trigger the User Event. After that auto-wired the org.springframework.context.ApplicationEventPublisher. Finally, pass the UserEvent through the publisher.

5) How to Run and Test it

We were using the IntelliJ to develop. Right click on the Application.java and select the Run App. Finally, send following GET request.

6) Conditional Event Handling

Let say, we want to handle specific events which fulfill specific condition(s). We can use SpEL to create conditions. For an example, the application wants to process all user events which are related to admin users.

Modified the UserEvent.java as following.

Then modified the UserEventListener.java.

http://localhost:8080/user/smith/admin/true

http://localhost:8080/user/smith/admin/false

When the admin is true, it handles the event.

7) Async Events

By default, the Spring Event Listeners works synchronously that means event publishing thread block until complete it. But that process takes a reasonable time we can handle it asynchronously using @Async.

 


Related Post

26182total visits,9visits today

RSS
Follow by Email
Facebook
Facebook
Google+
http://mydevgeek.com/spring-4-3-event-listener
Twitter