網站首頁 編程語言 正文
這里寫自定義目錄標題
- 說明
- 1.自定義監聽器
- 1.1 自定義事件
- 2. 定義監聽器
- 3.配置監聽器
- 4. 發布事件
- 5. 啟動項目測試結果
- 6. 處理方法
說明
在最近項目開發中,需要在原有項目的基礎上需要對原有部分業務數據添加監控功能。所以第一時間想到了使用監聽器,事件觸發機制解決。沒想到在自定義事件和添加監聽器功能后,測試代碼出現了onApplicationEvent 事件被多次執行的問題。項目是 spring cloud,查閱資料說是由于有多個容器的原因。這里特別記錄下解決方式。
1.自定義監聽器
1.1 自定義事件
public class WayBillPlanEvent extends ApplicationEvent {
private String helloStr ="這是測試 監聽器 事件定義內容 ";
public WayBillPlanEvent(Object source) {
super(source);
}
public String getHelloStr() {
return helloStr;
}
public void setHelloStr(String helloStr) {
this.helloStr = helloStr;
}
}
2. 定義監聽器
@Component
public class WayBillPlanEventListener{
@Component
public class WayBillPlanEventListener implements ApplicationListener<WayBillPlanEvent> {
@Async
public void onApplicationEvent(WayBillPlanEvent wayBillPlanEvent) {
System.out.println("WayBillPlanEventListener : " + wayBillPlanEvent.getSource().toString() + wayBillPlanEvent.getHelloStr());
}
}
3.配置監聽器
監聽器配置有多種方式,這里通過 spring.factories 文件配置,
注意,文件路徑為 \resources\META-INF\spring.factories
文件內容:
org.springframework.context.ApplicationListener=\
com.onitor.listeners.WayBillPlanEventListener
4. 發布事件
@Resource
private ApplicationContext applicationContext;
public void listenerNoticeServiceImpl(){
WayBillPlanEvent wayBillPlanEvent = new WayBillPlanEvent(this);
applicationContext.publishEvent(wayBillPlanEvent);
}
5. 啟動項目測試結果
監聽器的 onApplicationEvent 方法被執行了多次。
6. 處理方法
通過注解 @EventListener 可解決 onApplicationEvent 被執行多次的問題。注意通過 @EventListener 注解 需刪除 \resources\META-INF\spring.factories 中 ApplicationListener 的配置。
代碼
@Component
public class WayBillPlanEventListener{
@EventListener
@Async
public void onApplicationEvent(WayBillPlanEvent wayBillPlanEvent) {
System.out.println("WayBillPlanEventListener : " + wayBillPlanEvent.getSource().toString() + wayBillPlanEvent.getHelloStr());
}
}
原文鏈接:https://blog.csdn.net/daxues_/article/details/125408630
相關推薦
- 2022-12-08 重溫Python基礎之列表操作_python
- 2022-05-18 React?Hook之使用Effect?Hook的方法_React
- 2023-01-18 C#實現設置電腦顯示器參數_C#教程
- 2023-07-26 webpack提供構建速度之打包開啟多進程(thead)
- 2022-12-12 C語言入門之查找子串問題_C 語言
- 2022-05-29 react實現可播放的進度條_React
- 2021-12-16 .NET中的狀態機庫Stateless的操作流程_實用技巧
- 2023-08-28 react:使用 moment 來獲取日期
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支