SpringBoot事件发布和监听的示例分析
导读:本文共1825.5字符,通常情况下阅读需要6分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 概述ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。事件监听的作用与消息队列有一点类似。事件监听的结构主要有三个部分组成... ...
目录
(为您整理了一些要点),点击可以直达。概述
ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。事件监听的作用与消息队列有一点类似。
事件监听的结构
主要有三个部分组成:
发布者Publisher
事件Event
监听者Listener
Publisher,Event和Listener的关系
事件
我们自定义事件MyTestEvent继承了ApplicationEvent,继承后必须重载构造函数,构造函数的参数可以任意指定,其中source参数指的是发生事件的对象,一般我们在发布事件时使用的是this关键字代替本类对象,而user参数是我们自定义的注册用户对象,该对象可以在监听内被获取。
@GetterpublicclassMyTestEventextendsApplicationEvent{privatestaticfinallongserialVersionUID=1L;privateUseruser;publicMyTestEvent(Objectsource,Useruser){super(source);this.user=user;}}
发布者
事件发布是由ApplicationContext对象管控的,我们发布事件前需要注入ApplicationContext对象调用publishEvent方法完成事件发布。
ApplicationEventPublisher applicationEventPublisher 虽然声明的是ApplicationEventPublisher,但是实际注入的是applicationContext
@RestController@RequestMapping("/test")publicclassTestController{@AutowiredApplicationContextapplicationContext;@AutowiredApplicationEventPublisherapplicationEventPublisher;@GetMapping("testEvent")publicvoidtest(){applicationEventPublisher.publishEvent(newMyTestEvent("dzf-casfd-111",newUser("dzf-625096527-111","xiaoming",19)));applicationEventPublisher.publishEvent(newMyTestEvent("dzf-49687489-111",newUser("dzf-625096527-111","xiaowang",20)));}}
监听者
面向接口编程,实现ApplicationListener接口
@ComponentpublicclassMyTestListenerimplementsApplicationListener<MyTestEvent>{@OverridepublicvoidonApplicationEvent(MyTestEventmyTestEvent){System.out.println("MyTestListener:"+myTestEvent.getUser());}}
使用@EventListener注解配置
@ComponentpublicclassMyTestListener2{@EventListener(MyTestEvent.class)publicvoidonApplicationEvent(MyTestEventmyTestEvent){System.out.println("MyTestListener2:"+myTestEvent.getUser());}}
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
SpringBoot事件发布和监听的示例分析的详细内容,希望对您有所帮助,信息来源于网络。