Spring boot event listener annotation @EventListener is used to create a method that listens for spring boot events. A spring boot event is published using the ApplicationEventPublisher class. The @EventListener annotated methods are invoked when an event is published using the ApplicationEventPublisher class. The @Async annotation enables event listeners to execute in async mode. The @Order annotation controls the execution order of the spring boot event listener methods. In this post, we’ll look at how to use spring boot event listener annotations to publish events and create event listeners with examples.

Spring boot events are synchronous by default, which means that the publisher thread is blocked until all listeners have completed processing the event. The @Async annotation enables event listeners to execute in async mode. The @Order annotation controls the execution order of the spring boot event listener methods. The spring boot events framework lets you to simply annotate a managed bean method with @EventListener to automatically register an ApplicationListener matching the method’s signature.

The ApplicationEventPublisher class will publish an event. An event class is created by extending the ApplicationEvent class. The data will be sent between the publisher and listener classes via the even class. The ApplicationListener Interface is used to create the listener class. Alternatively, the annotation @EventListener is used in a method that will listen for and execute events.



Application Event Class

The ApplicationEvent class is used to created a custom event class. The custom event class is a java bean class which extends the ApplicationEvent class. The event class contains getter and setter methods of the properties that will be transferred from publisher to the listener class.

MyCustomApplicationEvent.java

package com.yawintutor;

import org.springframework.context.ApplicationEvent;

@SuppressWarnings("serial")
public class MyCustomApplicationEvent extends ApplicationEvent {

	private String name;
	
	public MyCustomApplicationEvent(Object source, String name) {
		super(source);
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}	
}


ApplicationEventPublisher Implementation

The publishEvent api in the ApplicationEventPublisher class is used to publish a spring boot application event. Create the application event object and provide it as a parameter to the publishEvent method. The publishEvent method sends data to all listener classes via the ApplicationEvent class. The publishEvent method runs synchronously and finishes once all of the listener methods have completed.

TestController.java

package com.yawintutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

	@Autowired
	ApplicationEventPublisher publisher;
	
	@GetMapping(value = "/publish")
	public String publish() {
		System.out.println("TestController : publishing the message");

		MyCustomApplicationEvent event = new MyCustomApplicationEvent(this, "MyEvent");
		System.out.println("MyCustomApplicationEventPublisher : Source : "+this.getClass().getName() + ", Message : "+ event.getName());
		publisher.publishEvent(event);
		
		System.out.println("TestController : published the message");
		return "Published";
	}
}


Listener @EventListener annotation

The @EventListener annotation is applied to the listener methods. The @EventListener annotated methods are automatically identified by the Spring Boot events framework and converted into a listener class. The @EventListener annotated methods will be called automatically if the application event publisher publishes an event.

The @Order annotation specifies the order in which the listener methods should be called. If no @Order is given, the order of execution will be determined by the spring boot events framework.

MyCustomApplicationListener.java

package com.yawintutor;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;

@Configuration
public class MyCustomApplicationListener {

	@EventListener
	@Order(1)
	public void listener1(MyCustomApplicationEvent event) {
		System.out.println("Listener1      : Source : "+event.getSource().getClass().getName() + ", Message : "+ event.getName());	
	}

	@EventListener
	@Order(2)
	public void listener2(MyCustomApplicationEvent event) {
		System.out.println("Listener2      : Source : "+event.getSource().getClass().getName() + ", Message : "+ event.getName());	
	}

	@EventListener
	@Order(3)
	public void listener3(MyCustomApplicationEvent event) {
		System.out.println("Listener3      : Source : "+event.getSource().getClass().getName() + ", Message : "+ event.getName());	
	}
}


Spring Boot Main Method

The spring boot main method will be called if the spring boot application starts. The spring boot main method will be shown as below.

SpringBootEventsApplication.java

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootEventsApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootEvents2Application.class, args);
	}
}


Pom.xml file

The pom.xml file for the spring boot events is provided below. The usage of the spring boot events does not necessitate any extra dependencies.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>SpringBootEvents</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootEvents</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


How to execute

Start the spring boot application and navigate to the URL shown below in the browser.

http://localhost:8080/publish

The console log below demonstrates how the publisher publishes the event and how events are listened to in the @EventListener annotated methods.

TestController : publishing the message
MyCustomApplicationEventPublisher : Source : com.yawintutor.TestController, Message : MyEvent
Listener1      : Source : com.yawintutor.TestController, Message : MyEvent
Listener2      : Source : com.yawintutor.TestController, Message : MyEvent
Listener3      : Source : com.yawintutor.TestController, Message : MyEvent
TestController : published the message



Leave a Reply