search
HomeJavajavaTutorialHow to use ApplicationEvent and ApplicationListener in SpringBoot

How to use ApplicationEvent and ApplicationListener in SpringBoot

May 13, 2023 pm 07:46 PM
springbootapplicationlistenerapplicationevent

In this model, there are two important classes, one is event and the other is listening. Events must inherit the ApplicationEvent class, and monitoring must implement the ApplicationListener interface.

1. Develop ApplicationEvent event

The event is actually the message body we want to send. This generally needs to be encapsulated according to our actual business. What type of data is needed is what to use. Type, add which fields are needed. Let's give a case.

package com.lsqingfeng.springboot.applicationEvent;
 
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;
 
/**
 * @className: MyApplicationEvent
 * @description: 事件封装
 * @author: sh.Liu
 * @date: 2022-03-23 14:41
 */
@Getter
@Setter
@ToString
public class MyApplicationEvent extends ApplicationEvent {
 
    private Integer age;
 
    private String name;
 
    /**
     * 需要重写构造方法
     * @param source
     * @param name
     * @param age
     */
    public MyApplicationEvent(Object source, String name, Integer age) {
        super(source);
        this.name = name;
        this.age = age;
    }
}

2. Develop the listener

The listener is equivalent to the consumer of our MQ. When there is time to push it, the listener code can be executed. Here we set our event type through generics.

package com.lsqingfeng.springboot.applicationEvent;
 
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
 
/**
 * @className: MyApplicationEventListener
 * @description:事件监听器
 * @author: sh.Liu
 * @date: 2022-03-23 14:50
 */
@Component
public class MyApplicationEventListener implements ApplicationListener<MyApplicationEvent> {
 
    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
        System.out.println("收到消息:" + event);
    }
}

3. Push events

Push events require the use of ApplicationEventPublisher. This object is already in the container when the Spring container is loaded. So we can inject it directly or use ApplicationContext, because ApplicationContext itself inherits ApplicationEventPublisher. Let's verify it through a Controller.

package com.lsqingfeng.springboot.controller;
 
import com.lsqingfeng.springboot.applicationEvent.MyApplicationEvent;
import com.lsqingfeng.springboot.base.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @className: ApplicationEventController
 * @description:
 * @author: sh.Liu
 * @date: 2022-03-23 15:21
 */
@RestController
@RequestMapping("event")
public class ApplicationEventController {
 
    @Autowired
    private ApplicationContext applicationContext;
 
    @RequestMapping("/push")
    public Result pushEvent(){
        MyApplicationEvent myApplicationEvent = new MyApplicationEvent(this,"zhangsan", 10);
        applicationContext.publishEvent(myApplicationEvent);
        return Result.success();
    }
 
    @RequestMapping("/push3")
    public Result pushEvent2(){
        applicationContext.publishEvent("大家好");
        return Result.success();
    }
}

We define two push methods. One pushes our MyApplicationEvent type, and another method pushes a string.

When we call the first method, the console can print out the data information we pushed.

How to use ApplicationEvent and ApplicationListener in SpringBoot

When calling the push string, our listener will not execute because our interceptor has added the generic MyApplicationEvent, which means it will only listen to MyApplicationEvent. type of message. Other types of messages will not be listened to.

What will be the effect if we remove generics? Let’s try it.

How to use ApplicationEvent and ApplicationListener in SpringBoot

Every push will send two messages (there may be some internal mechanism, I don’t care), but both are printed, indicating that if generics are not added, no matter who pushes , messages can be received here.

4. Implementing the listener using annotations

In addition to developing the listener by implementing the interface above, we can also implement it through annotations. The specific code is as follows.

package com.lsqingfeng.springboot.applicationEvent;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
/**
 * @className: MyApplicationEventListener2
 * @description: 注解实现监听器
 * @author: sh.Liu
 * @date: 2022-03-23 15:56
 */
@Component
public class MyApplicationEventListener2 {
 
    @EventListener
    public void onEvent(MyApplicationEvent event){
        System.out.println("收到消息2:" + event);
    }
}

The @EventListener annotation is added here to represent that this is a listener. The method name is arbitrary, and the parameters in the method represent the event types to be monitored.

Call the push method again:

How to use ApplicationEvent and ApplicationListener in SpringBoot

It is found that the data of both listeners will be printed. Everyone should pay attention to this feature.

The above is the detailed content of How to use ApplicationEvent and ApplicationListener in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft