日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot中使用ApplicationListener和ApplicationEvent /@EventListener监听事件

發布時間:2024/9/30 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot中使用ApplicationListener和ApplicationEvent /@EventListener监听事件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 自定義一個事件類
  • 監聽類:
  • 事件發布者
  • 改用@EventListener注解:
    • 總結


自定義一個事件類

public class OnRegistrationCompleteEvent extends ApplicationEvent {private final User user;public OnRegistrationCompleteEvent(final User user) {super(user);System.out.println("登錄/注冊了一個"+user.toString());this.user = user;}public User getUser() {return user;} }

監聽類:

@Component public class EventListener implements ApplicationListener<OnRegistrationCompleteEvent> {@Override@NonNullpublic void onApplicationEvent(OnRegistrationCompleteEvent event) {//事件發生后回調的方法System.out.println("監聽"+event.getUser().toString());} }

事件發布者

在業務層中注入publisher

@Service public class UserServiceImpl implements IUserService { @AutowiredUserMapper userMapper; @Autowired private ApplicationEventPublisher publisher;public ResponseResult insert(User record) {userMapper.insert(record);publisher.publishEvent(new OnRegistrationCompleteEvent(record));return ResponseResult.success(record);}}

ApplicationEventPublisher是ApplicationContext的父接口之一。這接口的作用是:Interface that encapsulates event publication functionality.

功能就是發布事件,也就是把某個事件告訴的所有與這個事件相關的監聽器。
  
現在插入一條數據進行測試:

如果刪掉 publisher.publishEvent(new OnRegistrationCompleteEvent(record));這句話會發現事件并沒有被監聽

改用@EventListener注解:

修改上面的監聽類,不再繼承ApplicationListener

@Componentpublic class EmailSendListener {@NonNull@EventListener(classes=OnRegistrationCompleteEvent.class)public void onApplicationEvent(OnRegistrationCompleteEvent event) {//事件發生后回調的方法System.out.println("監聽"+event.getUser().toString());} }

再次插入數據:

一樣可以起到監聽作用。

總結

目前結論:需要自定義事件,監聽者,發布者。
監聽者類需要加@component注解交由spring管理,可以選擇繼承ApplicationEvent 也可以加@EventListener注解的方式
發布者發布事件后所有監聽器將能接收到信息,回調監聽到以后的方法
基本上牽涉到事件(Event)方面的設計,就離不開觀察者模式,ApplicationContext 的事件機制主要通過 ApplicationEvent 和 ApplicationListener 這兩個接口來提供的,和 Java swing 中的事件機制一樣。即當 ApplicationContext 中發布一個事件時,所有擴展了 ApplicationListener 的 Bean都將接受到這個事件,并進行相應的處理。

ApplicationContext 擴展了 ResourceLoader(資源加載器)接口,從而可以用來加載多個Resource,而 BeanFactory 是沒有擴展 ResourceLoader

總結

以上是生活随笔為你收集整理的springboot中使用ApplicationListener和ApplicationEvent /@EventListener监听事件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。