Spring Boot Event Listener Example (2024)
In this tutorial, we'll demonstrate how to use @EventListener
in Spring Boot.
Q: What is Spring Boot event listeners?
Ans:
Annotation for Spring Boot event listeners A method that listens for spring boot events is created
using @EventListener
. The ApplicationEventPublisher
class is used to
broadcast a spring boot event.
When an event is published with the ApplicationEventPublisher
class, the @EventListener
annotated
methods are called.
A listener can be defined in two ways. Either the @EventListener
annotation or the
ApplicationListener
interface can be used.
Q: What is listener in event handling?
Ans:
When an event occurs, a listener object is notified.
Q: Is it possible to have Publisher in one Spring Boot application and Listener in another
application?
Ans:
Publisher and Listener of the EventListener can be handle within only one Spring application. We'll need to use an external message queue to spread them over the network (e.g. Kafka, RabbitMQ).
Create Spring Boot application
Create Spring Boot application from Spring Initializr.
Project Structure
Add Dependencies
Add spring-boot-starter-web
dependency in 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.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>SpringBootEventListener</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootEventListener</name>
<description>Spring Boot Event Listener Example</description>
<properties>
<java.version>1.8</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>
Take a look at our suggested posts:
Spring Boot Event Publisher
- The
ApplicationEventPublisher
is used to broadcast a spring boot event. When an event is published with theApplicationEventPublisher
, the@EventListener
annotated methods are called. - Create two publishing methods, one for the Email Event object and the other for the
String
message.
package com.techgeeknext.publisher;
import com.techgeeknext.event.EmailEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component
public class EmailPublisher {
private final ApplicationEventPublisher eventPublisher;
EmailPublisher(ApplicationEventPublisher publisher) {
this.eventPublisher = publisher;
}
public void publishEmailEvent(EmailEvent event) {
eventPublisher.publishEvent(event);
}
public void publishMsgEvent(String msg) {
eventPublisher.publishEvent(msg);
}
}
Spring Boot Event Listener
- A listener can be defined in two ways. Either the
@EventListener
annotation or theApplicationListener
interface can be used. - Spring enables to create and publish custom events that are synchronous by default. This means that the publisher thread is blocked until all listeners have completed processing the event.
- To have an event listener execute in async mode, just add the
@Async
annotation to that listener. - We have created two listeners, one for listening Email Event and other for
String
message event.
package com.techgeeknext.listener;
import com.techgeeknext.event.EmailEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class EmailListener {
@Async
@EventListener
void sendMsgEvent(EmailEvent emailEvent) {
System.out.println("==EmailListener 1 ==="+emailEvent.getMessage());
}
@Async
@EventListener
void sendMsgEvent(String message) {
System.out.println("==EmailListener 2 ==="+message);
}
}
Controller to test Spring Boot Event Listener
Spring Boot Event Listener can be used for cross-cutting issues such as sending email in response to an event or performing a task if a business event/exception occurs in the application.
Refer Spring Boot Email Example to send this event.
package com.techgeeknext.controller;
import com.techgeeknext.event.EmailEvent;
import com.techgeeknext.publisher.EmailPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
@Autowired
EmailPublisher emailPublisher;
@GetMapping("/notify/event")
public void publishEvent(){
emailPublisher
.publishEmailEvent
(new EmailEvent("Employee added."));
emailPublisher
.publishMsgEvent
("Exception occurred.");
}
}
Enable Async in Spring Boot Application
@EnableAsync
is used in Java Spring Boot application to enable asynchronous processing
and to run
@Async
methods. The @Async
methods execute in the background thread pool,
allowing other parallel
processes to continue uninterrupted.
package com.techgeeknext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class SpringBootEventListenerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootEventListenerApplication.class, args);
}
}
Test Spring Boot Event Listener Example
- Start the Spring Boot Application by running
spring-boot:run
or by running main class. Publish Event
Use GET method with end point http://localhost:8080/notify/event which will publish email event and exception message.- Listeners methods will be executed once the above rest endpoint is invoked. It will then print
the output as displayed in the console below.
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.7) 12:38:44.066 INFO 35440 --- [main] c.t.SpringBootEventListenerApplication : Starting SpringBootEventListenerApplication using Java 1.8.0_91 on (D:\SpringBootEventListener\target\classes started by in D:\SpringBootEventListener) 12:38:44.070 INFO 35440 --- [main] c.t.SpringBootEventListenerApplication : No active profile set, falling back to 1 default profile: "default" 12:38:45.623 INFO 35440 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 12:38:45.632 INFO 35440 --- [main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 12:38:45.632 INFO 35440 --- [main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.62] 12:38:45.764 INFO 35440 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 12:38:45.764 INFO 35440 --- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1654 ms 12:38:46.131 INFO 35440 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 12:38:46.138 INFO 35440 --- [main] c.t.SpringBootEventListenerApplication : Started SpringBootEventListenerApplication in 2.441 seconds (JVM running for 2.784) 12:38:49.599 INFO 35440 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 12:38:49.599 INFO 35440 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 12:38:49.600 INFO 35440 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms ==EmailListener 1 ===Employee added. ==EmailListener 2 ===Exception occurred.
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot Event Listener Example