本文主要是介绍观察者模式Spring之publishEvent事件处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
观察者模式Spring之publishEvent事件处理
- 一、使用场景
- 二、原理
- 三、事件触发 && 监听处理过程
- 四、代码实现
- 五、执行结果
- 六、源码下载
一、使用场景
这个一般什么时候使用,我们一般是在不同的bean直接进行信息传递,比如我们beanA的事件处理完后,需要beanB进行处理一些业务逻辑的时候这种情况就一般可以使用publish-event解决。
二、原理
ApplicationContext中的事件处理是通过ApplicationEvent类和ApplicationListener接口来提供的,通过ApplicationContext的publishEvent()方法发布到ApplicationListener;。
一个事件模型有三个组成部分:被监听对象source(也称为事件源),事件event和监听对象listener。事件发布者在发布事件的时候->通知事件的监听者。
首先,由监听对象注册监听回调函数(Callback),当事件源触发了事件后,监听对象会收到事件源的信息,然后决定如何对事件源进行处理,简要流程如下图所示。
三、事件触发 && 监听处理过程
(1) 使用 org.springframework.context 包下的 ApplicationContext.publishEvent(ApplicationEvent appEvent) 发布事件
(2) 使用 org.springframework.context.event 包下的 @EventListener(事件名) 监听事件并处理。
注意:
(1) ApplicationContext.publishEvent 默认是同步操作, 并非发布后不管的异步操作,发布事件后需要等 @EventListener 执行完。
(2) 如果需要开启异步操作需要在@EventListener上增加@Async 注解。
四、代码实现
(1)CustomEvent
/*** 用户事件监听** @author zhang*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomEvent {private String message;
}
(2)CustomEventListener
/*** @author zhang*/
@Component
public class CustomEventListener {@EventListener(CustomEvent.class)public void onApplicationEvent(CustomEvent customEvent) throws InterruptedException {System.out.println("监听器接受消息:"+ customEvent.getMessage());}
}
(3)CustomController
/*** @author zhang*/
@RestController
public class CustomController {@Resourceprivate ApplicationContext applicationContext;@RequestMapping("/helloListener")public String helloListener(){System.out.println("模拟执行某业务逻辑A!");System.out.println("=======AAA================");System.out.println("模拟执行某业务逻辑B-> 即A执行完成后执行业务逻辑B");System.out.println("事件开始发布消息!");applicationContext.publishEvent(new CustomEvent("你好啊"));System.out.println("=======BBB================");System.out.println("模拟执行某业务逻辑B执行完毕!");return "success";}
}
五、执行结果
六、源码下载
点我下载源码
参考文章
https://www.bianchengquan.com/article/568343.html
https://blog.csdn.net/sxlzs_/article/details/122497880
https://blog.csdn.net/wufagang/article/details/112759722
https://zhuanlan.zhihu.com/p/403365107
这篇关于观察者模式Spring之publishEvent事件处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!