当前位置: 首页 > news >正文

Spring Boot事件监听使用指南

Spring Boot事件监听使用指南

在Spring Boot中,事件监听是一种常见的设计模式,用于在事件发生时通知感兴趣的组件。通过事件监听机制,我们可以实现模块之间的松耦合,增强系统的可扩展性和可维护性。本文将详细介绍如何通过实现类和使用注解@EventListener的方式来实现事件监听。

什么是Spring事件

Spring事件是一种观察者模式的实现。Spring提供了一个事件发布-订阅模型,允许我们定义和监听事件。当事件发生时,事件发布者会发布事件,所有注册了该事件的监听器都会收到通知并作出相应的处理。

通过实现类的方式实现事件监听

1. 定义事件类

首先,我们需要定义一个事件类。事件类需要继承ApplicationEvent

import org.springframework.context.ApplicationEvent;public class CustomEvent extends ApplicationEvent {private String message;public CustomEvent(Object source, String message) {super(source);this.message = message;}public String getMessage() {return message;}
}

2. 发布事件

接下来,我们需要一个事件发布者来发布事件。可以在任意Spring Bean中发布事件。

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;@Component
public class CustomEventPublisher implements ApplicationEventPublisherAware {private ApplicationEventPublisher applicationEventPublisher;@Overridepublic void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {this.applicationEventPublisher = applicationEventPublisher;}public void publishEvent(String message) {CustomEvent event = new CustomEvent(this, message);applicationEventPublisher.publishEvent(event);}
}

3. 创建事件监听器

然后,我们需要创建一个事件监听器来处理事件。监听器需要实现ApplicationListener接口。

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {@Overridepublic void onApplicationEvent(CustomEvent event) {System.out.println("Received custom event - " + event.getMessage());}
}

4. 测试事件监听

最后,我们可以通过Spring Boot的入口类来测试事件监听的效果。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class EventDemoApplication implements CommandLineRunner {@Autowiredprivate CustomEventPublisher customEventPublisher;public static void main(String[] args) {SpringApplication.run(EventDemoApplication.class, args);}@Overridepublic void run(String... args) throws Exception {customEventPublisher.publishEvent("Hello, Spring Events!");}
}

启动应用程序,您应该会在控制台看到监听器输出的消息。

使用@EventListener注解实现事件监听

除了实现ApplicationListener接口,Spring还提供了另一种更简洁的方式来监听事件,即使用@EventListener注解。

1. 定义事件类

事件类与前面的定义相同。

import org.springframework.context.ApplicationEvent;public class CustomEvent extends ApplicationEvent {private String message;public CustomEvent(Object source, String message) {super(source);this.message = message;}public String getMessage() {return message;}
}

2. 发布事件

事件发布的方式也与前面相同。

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;@Component
public class CustomEventPublisher implements ApplicationEventPublisherAware {private ApplicationEventPublisher applicationEventPublisher;@Overridepublic void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {this.applicationEventPublisher = applicationEventPublisher;}public void publishEvent(String message) {CustomEvent event = new CustomEvent(this, message);applicationEventPublisher.publishEvent(event);}
}

3. 创建事件监听器

这次,我们使用@EventListener注解来定义事件监听器。

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Component
public class CustomEventListener {@EventListenerpublic void handleCustomEvent(CustomEvent event) {System.out.println("Received custom event - " + event.getMessage());}
}

4. 测试事件监听

通过Spring Boot的入口类来测试事件监听的效果,同样可以使用前面提供的测试代码。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class EventDemoApplication implements CommandLineRunner {@Autowiredprivate CustomEventPublisher customEventPublisher;public static void main(String[] args) {SpringApplication.run(EventDemoApplication.class, args);}@Overridepublic void run(String... args) throws Exception {customEventPublisher.publishEvent("Hello, Spring Events!");}
}

启动应用程序,您应该会在控制台看到监听器输出的消息。

总结

在Spring Boot中,事件监听机制提供了一种松耦合的组件间通信方式。通过实现ApplicationListener接口或使用@EventListener注解,我们可以轻松地实现事件监听。希望本文能够帮助您更好地理解和使用Spring Boot的事件监听机制。

相关文章:

  • 【鸿蒙】创建第⼀个鸿蒙项⽬
  • 分布式训练框架
  • Spring Boot启动与运行机制详解:初学者友好版
  • 51单片机定时器中断配置
  • QT day4
  • 开源一套Trados Sdlxliff 对比工具
  • 以太坊==使用IDE remix.ethereum搭配metamask发布合约到测试网
  • 【C++】优先队列的使用及模拟实现
  • MetaGPT: Merging Large Language Models Using Model Exclusive Task Arithmetic
  • Linux rm命令由于要删的文件太多报-bash: /usr/bin/rm:参数列表过长,无法删除的解决办法
  • AI:音乐创作的未来还是毁灭的序曲?
  • 在自托管基础设施上使用 GitOps 部署 MinIO
  • 数据通信与网络(五)
  • Oracle day10
  • 【Linux系统】多线程
  • 自己简单写的 事件订阅机制
  • 《微软的软件测试之道》成书始末、出版宣告、补充致谢名单及相关信息
  • CSS实用技巧干货
  • Golang-长连接-状态推送
  • jquery ajax学习笔记
  • markdown编辑器简评
  • MQ框架的比较
  • Mysql数据库的条件查询语句
  • Nacos系列:Nacos的Java SDK使用
  • Netty 框架总结「ChannelHandler 及 EventLoop」
  • python docx文档转html页面
  • SpriteKit 技巧之添加背景图片
  • 翻译--Thinking in React
  • 回流、重绘及其优化
  • 基于Vue2全家桶的移动端AppDEMO实现
  • 记一次和乔布斯合作最难忘的经历
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 排序算法之--选择排序
  • 如何在 Tornado 中实现 Middleware
  • 实战:基于Spring Boot快速开发RESTful风格API接口
  • 世界编程语言排行榜2008年06月(ActionScript 挺进20强)
  • 首页查询功能的一次实现过程
  • 通过npm或yarn自动生成vue组件
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • 正则表达式小结
  • puppet连载22:define用法
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • ​Linux·i2c驱动架构​
  • # 执行时间 统计mysql_一文说尽 MySQL 优化原理
  • #define、const、typedef的差别
  • #mysql 8.0 踩坑日记
  • #NOIP 2014# day.1 T3 飞扬的小鸟 bird
  • #我与Java虚拟机的故事#连载14:挑战高薪面试必看
  • (20)目标检测算法之YOLOv5计算预选框、详解anchor计算
  • (libusb) usb口自动刷新
  • (PWM呼吸灯)合泰开发板HT66F2390-----点灯大师
  • (笔试题)分解质因式
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • ./indexer: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object fil
  • .apk文件,IIS不支持下载解决