搜索
首页Javajava教程SpringBoot中ApplicationEvent和ApplicationListener怎么使用

SpringBoot中ApplicationEvent和ApplicationListener怎么使用

May 13, 2023 pm 07:46 PM
springbootapplicationlistenerapplicationevent

在这个模型中,有两个重要的类,一个是事件,一个是监听。事件要继承ApplicationEvent类,监听要实现ApplicationListener接口。

一、开发ApplicationEvent事件

事件其实就是我们要发送的消息体,这个一般要根据我们的实际业务进行封装,需要什么类型的数据,就是用什么类型,需要哪些字段就添加哪些字段。我们来给一个案例。

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;
    }
}

二、 开发监听器

监听器就相当于我们的MQ的消费者,当有时间推送过来的时候,监听器的代码就可以执行。这里通过泛型来设置好我们的事件类型。

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);
    }
}

三、推送事件

推送事件需要使用ApplicationEventPublisher。这个对象在Spring容器加载的时候就已经在容器中了。所以我们可以直接注入使用,也可以使用ApplicationContext,因为ApplicationContext本身就继承了ApplicationEventPublisher。 我们通过一个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();
    }
}

我们定义两个推送的方法。一个推送我们的MyApplicationEvent类型,还有一个方法推送一个字符串。

当我们调用第一个方法的时候,控制台可以打印出我们推送的数据信息。

SpringBoot中ApplicationEvent和ApplicationListener怎么使用

调用推送字符串的时候,我们的监听器不会执行,原因是我们的拦截器里已经加了泛型MyApplicationEvent,也就是只会监听MyApplicationEvent类型的消息。其他类型的消息不会被监听到。

那如果我们把泛型去掉会有什么效果呢,我们来试试。

SpringBoot中ApplicationEvent和ApplicationListener怎么使用

每次推送都会发送两条(可能有什么内部机制,不管了),但是两个都打印了,说明如果不加泛型,不管谁推,这边都能收到消息。

四、注解方式实现监听器

除了上面的通过实现接口的方式开发监听器,我们还可以通过注解的方式来实现,具体代码如下。

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);
    }
}

这里加入了@EventListener 注解代表了这是一个监听器。方法名随意,方法里的参数代表监听的事件类型。

再次调用push方法:

SpringBoot中ApplicationEvent和ApplicationListener怎么使用

发现两个监听器的数据都会打印。这一特点大家要注意一下。

以上是SpringBoot中ApplicationEvent和ApplicationListener怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
JVM性能与其他语言JVM性能与其他语言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台独立性:使用示例Java平台独立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架构:深入研究Java虚拟机JVM架构:深入研究Java虚拟机May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM与操作系统有关吗?JVM:JVM与操作系统有关吗?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性May 14, 2025 am 12:05 AM

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具