Spring事件Application Event原理详解
作者:21Java 时间:2021-10-03 19:43:45
这篇文章主要介绍了Spring 事件Application Event原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Spring 的事件(Application Event)为 Bean 与 Bean 之间的消息通信提供了支持。当一个 Bean 处理完一个任务之后,希望另一个 Bean 知道并能做相应的处理,这时我们就需要让另一个 Bean 监听当前 Bean 所发送的事件。(观察者模式)
Spring 的事件需要遵循以下流程:
自定义事件,集成 ApplicationEvent。
定义事件 * ,实现 ApplicationListener。
使用容器发布事件。
以下代码基于 Spring Boot 实现
自定义事件
public class DemoEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
private String msg;
public DemoEvnet(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
事件监听者
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMsg();
System.out.println("接收到了消息:" + msg);
}
}
代码解释:
实现 ApplicaionListener 接口,并制定监听的时间类型。
使用 onApplicationEvent 方法对消息进行接收处理。
事件发布者
@Component
public class DemoPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(String msg) {
applicaionContext.publishEvent(new DemoEvent(this, msg));
}
}
代码解释:
注入 ApplicaionContext 用来发布事件。
使用 ApplicaionContext 的 publishEvent 方法来发布。
来源:https://www.cnblogs.com/peterpoker/p/10137856.html
标签:Spring,Application,Event,事件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Spring中的后置处理器BeanPostProcessor详解
2023-02-24 00:50:03
Android中隐藏状态栏和标题栏的方法汇总(隐藏状态栏、标题栏的五种方法)
2022-05-18 07:31:03
C#中#define后面只加一个参数的解释
2022-09-06 07:23:55
IntelliJ IDEA2022.3 springboot 热部署含静态文件(最新推荐)
2023-07-07 10:41:58
![](https://img.aspxhome.com/file/2023/6/86776_0s.jpg)
C#中动态显示当前系统时间的实例方法
2023-06-20 14:46:02
使用IDEA搭建一个简单的SpringBoot项目超详细过程
2022-07-19 11:43:58
![](https://img.aspxhome.com/file/2023/3/64033_0s.png)
C# 添加对System.Configuration.dll文件的引用操作
2022-03-05 22:20:31
![](https://img.aspxhome.com/file/2023/7/69807_0s.jpg)
Java IO流—异常及捕获异常处理 try…catch…finally
2023-03-14 07:35:52
![](https://img.aspxhome.com/file/2023/1/62401_0s.png)
JAVA演示阿里云图像识别API,印刷文字识别-营业执照识别
2022-04-21 15:05:22
Filter、Servlet、Listener的学习_动力节点Java学院整理
2021-08-12 00:05:49
![](https://img.aspxhome.com/file/2023/9/72529_0s.jpg)
C#操作XML方法详解
2022-11-10 21:21:14
JAXB简介_动力节点Java学院整理
2021-09-15 00:09:32
Android10 启动之SystemServer源码分析
2021-08-15 05:38:13
![](https://img.aspxhome.com/file/2023/9/93269_0s.png)
C#序列化与反序列化实例
2023-05-05 21:05:27
python只需30行代码就能记录键盘的一举一动
2023-06-27 18:22:12
![](https://img.aspxhome.com/file/2023/3/82403_0s.gif)
详解如何在SpringBoot中自定义参数解析器
2023-07-24 16:06:51
SpringBoot工程搭建打包、启动jar包和war包的教程图文详解
2022-05-04 22:09:10
![](https://img.aspxhome.com/file/2023/2/69892_0s.png)
C#中OpenCVSharp实现轮廓检测
2022-04-03 17:38:11
![](https://img.aspxhome.com/file/2023/8/100178_0s.jpg)
Spring事务注解@Transactional失效的八种场景分析
2022-03-09 13:36:13
C#基于COM方式读取Excel表格的方法
2021-09-15 12:35:36