这篇文章主要介绍了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 方法来发布。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。