springBoot的事件机制GenericApplicationListener用法解析
作者:技术-刘腾飞 时间:2023-09-02 14:22:26
什么是ApplicationContext?
它是Spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。 ApplicationContext则是应用的容器。
Spring把Bean(object)放在容器中,需要用就通过get方法取出来。
ApplicationEvent
是个抽象类,里面只有一个构造函数和一个长整型的timestamp。
springboot的event的类型:
ApplicationStartingEvent
ApplicationEnvironmentPreparedEvent
ApplicationContextInitializedEvent
ApplicationPreparedEvent
ContextRefreshedEvent
ServletWebServerInitializedEvent
ApplicationStartedEvent
ApplicationReadyEvent
ApplicationListener
是一个接口,里面只有一个onApplicationEvent方法。所以自己的类在实现该接口的时候,要实现该方法。
ApplicationListener的封装类
GenericApplicationListener
GenericApplicationListenerAdapter
SmartApplicationListener
关系
如果在上下文中部署一个实现了ApplicationListener接口的bean,那么每当在一个ApplicationEvent发布到 ApplicationContext时,这个bean得到通知。其实这就是标准的Oberver设计模式。
注意
要配置META-INF/spring.factories文件,并在文件中实现
使用
// 第一种方式
public class AiInfluxdbApplicationListener implements GenericApplicationListener {
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public boolean supportsEventType(ResolvableType eventType) {
return ApplicationReadyEvent.class.isAssignableFrom(eventType.getRawClass());
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.print("here is ApplicationReadyEvent");
}
}
//第二种方式
public class ConfigApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
}
}
//META-INF/spring.factories文件定义
org.springframework.context.ApplicationListener=\
com.demotest.core.ApplicationStartListener
来源:https://www.cnblogs.com/frankltf/p/11383891.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java实现多文件上传功能
Java设计模式之模板方法模式Template Method Pattern详解
Java Swing JList列表框的实现
![](https://img.aspxhome.com/file/2023/4/80894_0s.gif)
C#8.0新语法using declaration
C#客户端HttpClient请求认证及数据传输
![](https://img.aspxhome.com/file/2023/8/100148_0s.jpg)
android 设置全屏的两种方法
![](https://img.aspxhome.com/file/2023/5/120145_0s.png)
Android开发之menu菜单
Java请求转发和请求重定向区别详解
![](https://img.aspxhome.com/file/2023/6/63786_0s.webp)
java生成xml格式文件的方法
![](https://img.aspxhome.com/file/2023/0/71660_0s.png)
opencv检测直线方法之投影法
![](https://img.aspxhome.com/file/2023/9/124169_0s.jpg)
Java解压zip文件的关键代码
基于C#动手实现网络服务器Web Server
![](https://img.aspxhome.com/file/2023/0/106490_0s.jpg)
android自定义View实现圆环颜色选择器
![](https://img.aspxhome.com/file/2023/8/125348_0s.gif)
Android截屏SurfaceView黑屏问题的解决办法
Java聊天室之实现一个服务器与多个客户端通信
![](https://img.aspxhome.com/file/2023/6/76636_0s.png)
SpringMVC RESTFul及REST架构风格介绍
![](https://img.aspxhome.com/file/2023/7/80917_0s.png)
关于C++一些特性的探究
Java 异步实现的几种方式小结
![](https://img.aspxhome.com/file/2023/9/71679_0s.png)
SpringBoot中的五种对静态资源的映射规则的实现
![](https://img.aspxhome.com/file/2023/4/108354_0s.jpg)