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

Spring Boot 监听器(Listeners)详细教程

Spring Boot 监听器概述

Spring Boot 监听器(Listeners)基于 Spring Framework 的事件机制(ApplicationEvent 和 ApplicationListener),用于在应用生命周期或自定义事件触发时执行特定逻辑。它们提供了一种松耦合的方式响应应用状态变化,常用于初始化资源、监控应用状态、执行异步任务等。

概念

事件类型

  • 内置系统事件:
  • ContextRefreshedEvent: ApplicationContext初始化或刷新时触发
  • ContextStartedEvent: ApplicationContext启动后触发
  • ContextStoppedEvent: ApplicationContext停止后触发
  • ContextClosedEvent: ApplicationContext关闭后触发
  • ApplicationStartedEvent: Spring Boot应用启动后触发
  • ApplicationReadyEvent: 应用准备就绪时触发(推荐在此执行启动逻辑)
  • ApplicationFailedEvent: 启动失败时触发
  • 自定义事件: 继承ApplicationEvent创建特定业务事件

监听器类型

接口实现: 实现ApplicationListener
注解驱动: 使用@EventListener注解方法
SmartApplicationListener: 支持事件类型过滤和顺序控制
简单说就是:

  • 事件(Event): 继承 ApplicationEvent 的类,表示一个事件(如应用启动、关闭等)。
  • 监听器(Listener): 实现 ApplicationListener 接口、SmartApplicationListener接口或使用 @EventListener注解的组件,用于响应事件。
  • 事件发布(Publisher): 通过 ApplicationEventPublisher 发布事件。

最佳使用场景

在这里插入图片描述

自定义事件

步骤1:定义事件类

public class OrderCreateEvent extends ApplicationEvent {private String orderId;public OrderCreateEvent(Object source, String orderId) {super(source);this.orderId = orderId;}public String getOrderId() {return orderId;}
}

步骤2:发布事件

@Service
public class OrderService {@Autowiredprivate ApplicationEventPublisher eventPublisher;public void createOrder(Order order) {// 创建订单逻辑...eventPublisher.publishEvent(new OrderCreateEvent(this, order.getId()));}
}

事件监听

方式1:实现ApplicationListener接口

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;public class SystemStartupListener implements ApplicationListener<ApplicationReadyEvent> {@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {System.out.println("=== 应用启动完成,执行初始化操作 ===");// 初始化业务数据...}
}

public class OrderCreateEventListener implements ApplicationListener<OrderCreateEvent> {@Overridepublic void onApplicationEvent(OrderCreateEvent event) {System.out.println("=== 执行操作 ===");// 初始化业务数据...}
}

方式2:使用@EventListener注解

import org.springframework.context.event.EventListener;
import org.springframework.boot.context.event.ApplicationStartedEvent;@Component
public class AnnotationBasedListener {@EventListenerpublic void handleStartedEvent(ApplicationStartedEvent event) {System.out.println("=== 应用启动事件捕获 ===");}
}
@Component
public class AnnotationBasedListener {@EventListenerpublic void handleStartedEvent(OrderCreateEvent event) {System.out.println("=== 执行操作 ===");}
}

方式3:实现SmartApplicationListener接口

@Slf4j
@Component
public class MyTask implements SmartApplicationListener {@Overridepublic boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {return eventType == MyEvent.class || eventType == OrderCreateEvent.class;}@Overridepublic int getOrder() {return 0;}@Overridepublic void onApplicationEvent(ApplicationEvent event) {if (event instanceof OrderCreateEvent) {log.info("监听到 OrderCreateEvent...");}if (event instanceof MyEvent) {log.info("监听到 MyEvent...");MyEvent myEvent = (MyEvent) event;System.out.println("时间:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());}}
}

在这里插入图片描述

高级配置

监听器顺序控制

    @EventListener@Order(Ordered.HIGHEST_PRECEDENCE) // 最高优先级public void handleOrderEvent(OrderCreateEvent event) {System.out.println("收到订单创建事件,订单ID:" + event.getOrderId());// 发送通知、更新统计...}

异步事件处理

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {@Overridepublic Executor getAsyncExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.initialize();return executor;}
}
// 可进行如下替换
@EventListener
@Async
public void asyncHandleEvent(MyEvent event) {// 异步执行
}

条件过滤

@EventListener(condition = "#event.orderId.startsWith('VIP')")
public void handleVipOrder(OrderCreateEvent event) {// 只处理VIP订单
}
http://www.xdnf.cn/news/549505.html

相关文章:

  • 为什么以太网一端配置为自协商(Auto-negotiation),另一端强制为**全双工(Full Duplex)**时,最终状态是自协商端降级为 半双工
  • Spring Boot中如何使用RabbitMQ?
  • 离线环境破局:聚客AI无外网部署Dify的依赖镜像打包与增量更新方案
  • 第三十天打卡
  • 3D几何建模引擎3D ACIS Modeler核心功能深度解读
  • ES(Elasticsearch) 基本概念(一)
  • 【Linux】初见,基础指令(续)
  • Linux第十一讲:信号
  • 构建自动收集并总结互联网热门话题的网站
  • 进程间通信(IPC)常用方式对比
  • 当PLC遇上电焊机器人:EtherCAT转CANopen上演工业级“语言翻译官”
  • DP2 跳台阶【牛客网】
  • [面试精选] 0001. 两数之和
  • 人工智能的“歧视”:“她数据”在算法运行中隐形
  • C46-二维数组与指针的总结
  • VUE3 中的 ResizeObserver 警告彻底解决方案
  • C#:多线程Task使用
  • c++使用protocol buffers
  • JS实现古诗竖排从右至左
  • 谈谈jvm的调优思路
  • c++学习方向选择说明
  • [软件工程]第二章题目汇总
  • MySQL 8.0窗口函数详解
  • 48、c# 中 IList 接⼝与List的区别是什么?
  • Gin--Blog项目-flags文件解析
  • RK3576 Android 14.0 SDK开发指南(第一集)
  • 丝杆升降机在锂电行业的自动化应用有什么?
  • Unity-编辑器扩展
  • 2025年护网行动蓝队防御全解析:构建智能动态防御体系
  • Raft算法学习(1)博士论文大纲