Spring事件ApplicationEvent原理详解
这篇⽂章主要介绍了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;springframework事务
}
public void setMsg(String msg) {
this.msg = msg;
}
}
事件监听者
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
public void onApplicationEvent(DemoEvent event) {
String msg = Msg();
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 ⽅法来发布。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。