Spring Boot 監(jiān)聽器Listeners詳細(xì)教程(最新整理)
Spring Boot 監(jiān)聽器概述
Spring Boot 監(jiān)聽器(Listeners)基于 Spring Framework 的事件機(jī)制(ApplicationEvent 和 ApplicationListener),用于在應(yīng)用生命周期或自定義事件觸發(fā)時(shí)執(zhí)行特定邏輯。它們提供了一種松耦合的方式響應(yīng)應(yīng)用狀態(tài)變化,常用于初始化資源、監(jiān)控應(yīng)用狀態(tài)、執(zhí)行異步任務(wù)等。
概念
事件類型
- 內(nèi)置系統(tǒng)事件:
- ContextRefreshedEvent: ApplicationContext初始化或刷新時(shí)觸發(fā)
- ContextStartedEvent: ApplicationContext啟動(dòng)后觸發(fā)
- ContextStoppedEvent: ApplicationContext停止后觸發(fā)
- ContextClosedEvent: ApplicationContext關(guān)閉后觸發(fā)
- ApplicationStartedEvent: Spring Boot應(yīng)用啟動(dòng)后觸發(fā)
- ApplicationReadyEvent: 應(yīng)用準(zhǔn)備就緒時(shí)觸發(fā)(推薦在此執(zhí)行啟動(dòng)邏輯)
- ApplicationFailedEvent: 啟動(dòng)失敗時(shí)觸發(fā)
- 自定義事件: 繼承ApplicationEvent創(chuàng)建特定業(yè)務(wù)事件
監(jiān)聽器類型
接口實(shí)現(xiàn): 實(shí)現(xiàn)ApplicationListener
注解驅(qū)動(dòng): 使用@EventListener注解方法
SmartApplicationListener: 支持事件類型過濾和順序控制
簡單說就是:
- 事件(Event): 繼承 ApplicationEvent 的類,表示一個(gè)事件(如應(yīng)用啟動(dòng)、關(guān)閉等)。
- 監(jiān)聽器(Listener): 實(shí)現(xiàn) ApplicationListener 接口、SmartApplicationListener接口或使用 @EventListener注解的組件,用于響應(yīng)事件。
- 事件發(fā)布(Publisher): 通過 ApplicationEventPublisher 發(fā)布事件。
最佳使用場景

自定義事件
步驟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:發(fā)布事件
@Service
public class OrderService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void createOrder(Order order) {
// 創(chuàng)建訂單邏輯...
eventPublisher.publishEvent(new OrderCreateEvent(this, order.getId()));
}
}事件監(jiān)聽
方式1:實(shí)現(xiàn)ApplicationListener接口
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
public class SystemStartupListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("=== 應(yīng)用啟動(dòng)完成,執(zhí)行初始化操作 ===");
// 初始化業(yè)務(wù)數(shù)據(jù)...
}
}public class OrderCreateEventListener implements ApplicationListener<OrderCreateEvent> {
@Override
public void onApplicationEvent(OrderCreateEvent event) {
System.out.println("=== 執(zhí)行操作 ===");
// 初始化業(yè)務(wù)數(shù)據(jù)...
}
}方式2:使用@EventListener注解
import org.springframework.context.event.EventListener;
import org.springframework.boot.context.event.ApplicationStartedEvent;
@Component
public class AnnotationBasedListener {
@EventListener
public void handleStartedEvent(ApplicationStartedEvent event) {
System.out.println("=== 應(yīng)用啟動(dòng)事件捕獲 ===");
}
}@Component
public class AnnotationBasedListener {
@EventListener
public void handleStartedEvent(OrderCreateEvent event) {
System.out.println("=== 執(zhí)行操作 ===");
}
}方式3:實(shí)現(xiàn)SmartApplicationListener接口
@Slf4j
@Component
public class MyTask implements SmartApplicationListener {
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return eventType == MyEvent.class || eventType == OrderCreateEvent.class;
}
@Override
public int getOrder() {
return 0;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof OrderCreateEvent) {
log.info("監(jiān)聽到 OrderCreateEvent...");
}
if (event instanceof MyEvent) {
log.info("監(jiān)聽到 MyEvent...");
MyEvent myEvent = (MyEvent) event;
System.out.println("時(shí)間:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());
}
}
}
高級配置
監(jiān)聽器順序控制
@EventListener
@Order(Ordered.HIGHEST_PRECEDENCE) // 最高優(yōu)先級
public void handleOrderEvent(OrderCreateEvent event) {
System.out.println("收到訂單創(chuàng)建事件,訂單ID:" + event.getOrderId());
// 發(fā)送通知、更新統(tǒng)計(jì)...
}異步事件處理
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.initialize();
return executor;
}
}
// 可進(jìn)行如下替換
@EventListener
@Async
public void asyncHandleEvent(MyEvent event) {
// 異步執(zhí)行
}條件過濾
@EventListener(condition = "#event.orderId.startsWith('VIP')")
public void handleVipOrder(OrderCreateEvent event) {
// 只處理VIP訂單
}到此這篇關(guān)于Spring Boot 監(jiān)聽器Listeners詳細(xì)教程的文章就介紹到這了,更多相關(guān)Spring Boot 監(jiān)聽器Listeners內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot中的ApplicationListener事件監(jiān)聽器使用詳解
- SpringBoot中使用監(jiān)聽器的方法詳解
- SpringBoot如何監(jiān)控Redis中某個(gè)Key的變化(自定義監(jiān)聽器)
- SpringBoot 過濾器、攔截器、監(jiān)聽器對比及使用場景分析
- Springboot項(xiàng)目監(jiān)聽器失效問題解決
- Spring boot通過HttpSessionListener監(jiān)聽器統(tǒng)計(jì)在線人數(shù)的實(shí)現(xiàn)代碼
- springboot 用監(jiān)聽器統(tǒng)計(jì)在線人數(shù)案例分析
- Spring Boot的listener(監(jiān)聽器)簡單使用實(shí)例詳解
相關(guān)文章
老生常談Java虛擬機(jī)垃圾回收機(jī)制(必看篇)
下面小編就為大家?guī)硪黄仙U凧ava虛擬機(jī)垃圾回收機(jī)制(必看篇)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
MybatisPlus使用queryWrapper如何實(shí)現(xiàn)復(fù)雜查詢
這篇文章主要介紹了MybatisPlus使用queryWrapper如何實(shí)現(xiàn)復(fù)雜查詢,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。2022-01-01
Java多線程的實(shí)現(xiàn)方式比較(兩種方式比較)
Java多線程實(shí)現(xiàn)方式有兩種,第一種是繼承Thread類,第二種是實(shí)現(xiàn)Runnable接口,兩種有很多差異,下面跟著本文一起學(xué)習(xí)吧2015-11-11
Java中java.sql.SQLException異常的正確解決方法(親測有效!)
SQLException是在Java中處理數(shù)據(jù)庫操作過程中可能發(fā)生的異常,通常是由于底層數(shù)據(jù)庫操作錯(cuò)誤或違反了數(shù)據(jù)庫規(guī)則而引起的,下面這篇文章主要給大家介紹了關(guān)于Java中java.sql.SQLException異常的正確解決方法,需要的朋友可以參考下2024-01-01

