当前位置:   article > 正文

观察者模式Spring之publishEvent事件处理_applicationcontext.publishevent

applicationcontext.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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

(2)CustomEventListener

/**
 * @author zhang
 */
@Component
public class CustomEventListener {

    @EventListener(CustomEvent.class)
    public void onApplicationEvent(CustomEvent customEvent) throws InterruptedException {
        System.out.println("监听器接受消息:"+ customEvent.getMessage());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

(3)CustomController

/**
 * @author zhang
 */
@RestController
public class CustomController {

    @Resource
    private 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";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

五、执行结果

在这里插入图片描述
在这里插入图片描述

六、源码下载

点我下载源码
在这里插入图片描述

参考文章
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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/153727
推荐阅读
相关标签
  

闽ICP备14008679号