spring-boot-learning-监听事件
Springboot扩展了Spring的ApplicatoionContextEvent,提供了事件:
ApplicationStartingEvent:框架启动事件
ApplicationEnvironmentPreparedEvent: springboot 对应Evironment已经准备完毕了,但是上下文还没有创建。
ApplicationContextInitializedEvent: 上下文初始化
ApplicationPreparedEvent: springboot 上下文context创建完成,但是bean没有完全加载
ApplicationStartedEvent: springboot 启动开始执行的事件
ApplicationReadyEvent : 调用Runners接口完毕
ApplicationFailedEvent:启动异常执行事件
* springboot自带的事件。
* ApplicationStartingEvent
* Spring Application启动事件。事件产生的时机为ApplicationListeners注册之后,Environment或ApplicationContext可用之前,
事件源为Spring Application自身,ApplicationStartingEvent在生命周期过程中可能会被修改,请谨慎使用。
* ApplicationEnvironmentPreparedEvent
* 事件产生的时机为Spring Application已经启动,Environment第一次可用。
* ApplicationPreparedEvent
* 事件产生的时机为Spring Application已经启动,Application Context已经完全准备好但是还没有进行刷新,在该阶段已经开始加载Bean定义并且Environment已经完全可用。
* ApplicationStartedEvent
* 事件产生的时机为Application Context已经完成刷新,ApplicationRunner application和CommandLineRunner调用之前。
* ApplicationReadyEvent
* Spring Application已经准备好对外提供服务。
* ApplicationFailedEvent
* 应用启动失败
自定义监听器的步骤:
1,建立监听类继承ApplicationListener
2, 继承方法onApplicationEvent
3, 在resource建立文件夹/META-INF/spring.factories
4, 文件里写入:
org.springframework.context.ApplicationListener=\
com.quan.sbrabbit.Listener.QuanListenerEnvPreparedEvent ,com.quan.sbrabbit.Listener.QuanListenerStartedEvent,com.quan.sbrabbit.Listener.QuanListenerPreparedEvent
/**
* spring boot 对应Enviroment已经准备完毕,但此时上下文context还没有创建。在该监听中获取到ConfigurableEnvironment
* 后可以对配置信息做操作,例如:修改默认的配置信息
*/ public class QuanListenerEnvPreparedEvent implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
MutablePropertySources sources =environment.getPropertySources();
if (sources != null){
Iterator<PropertySource<?>> iterator = sources.iterator();
while (iterator.hasNext()){
PropertySource<?> propertySource = iterator.next();
System.out.println(propertySource.getName());
System.out.println(propertySource.getSource());
System.out.println(propertySource.getClass());
}
System.out.println("监听到ApplicationEnvironmentPreparedEvent");
// for (PropertySource<?> p :
// sources) {
// System.out.println(p.getName());
// System.out.println(p.getSource());
// System.out.println(p.getClass());
// }
}
}
}
/**
* pring boot上下文context创建完成,但此时spring中的bean是没有完全加载完成的。
* 在获取完上下文后,可以将上下文传递出去做一些额外的操作。
* 值得注意的是:在该监听器中是无法获取自定义bean并进行操作的。
*/
public class QuanListenerPreparedEvent implements ApplicationListener<ApplicationPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
ConfigurableApplicationContext context = event.getApplicationContext();
context.toString();
System.out.println("监听到ApplicationPreparedEvent");
}
}
public class QuanListenerStartedEvent implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
SpringApplication application = event.getSpringApplication();
System.out.println(application);
//控制台或日志中会默认显示一个Banner,关闭这个东西
application.setBannerMode(Banner.Mode.OFF);
System.out.println("监听到applicationStartedEvent");
}
}
加入:
org.springframework.context.ApplicationListener=\
com.quan.sbrabbit.Listener.QuanListenerEnvPreparedEvent ,com.quan.sbrabbit.Listener.QuanListenerStartedEvent,com.quan.sbrabbit.Listener.QuanListenerPreparedEvent
运行输出:
监听到ApplicationEnvironmentPreparedEvent . ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.3.RELEASE) 2020-09-01 14:10:32.063 WARN 99192 --- [ main] o.s.boot.StartupInfoLogger : InetAddress.getLocalHost().getHostName() took 5004 milliseconds to respond. Please verify your network configuration (macOS machines may need to add entries to /etc/hosts).
2020-09-01 14:10:37.067 INFO 99192 --- [ main] com.quan.sbrabbit.SbrabbitApplication : Starting SbrabbitApplication on quandeMacBook-Pro.local with PID 99192 (/Users/quan/Desktop/ALLLL/sbrabbit/target/classes started by quan in /Users/quan/Desktop/ALLLL/sbrabbit)
2020-09-01 14:10:37.068 INFO 99192 --- [ main] com.quan.sbrabbit.SbrabbitApplication : No active profile set, falling back to default profiles: default
监听到ApplicationPreparedEvent
2020-09-01 14:10:37.491 INFO 99192 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Elasticsearch repositories in DEFAULT mode.
2020-09-01 14:10:37.505 INFO 99192 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 11ms. Found 0 Elasticsearch repository interfaces.
2020-09-01 14:10:37.509 INFO 99192 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Reactive Elasticsearch repositories in DEFAULT mode.
2020-09-01 14:10:37.511 INFO 99192 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 2ms. Found 0 Reactive Elasticsearch repository interfaces.
2020-09-01 14:10:37.762 INFO 99192 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9898 (http)
2020-09-01 14:10:37.768 INFO 99192 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-09-01 14:10:37.769 INFO 99192 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-09-01 14:10:37.838 INFO 99192 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-09-01 14:10:37.839 INFO 99192 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 740 ms
2020-09-01 14:10:38.006 INFO 99192 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-01 14:10:38.502 WARN 99192 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class org.springframework.data.geo.Point to interface java.util.Map as writing converter although it doesn't convert to a store-supported type! You might want to check your annotation setup at the converter implementation.
2020-09-01 14:10:38.502 WARN 99192 --- [ main] o.s.data.convert.CustomConversions : Registering converter from interface java.util.Map to class org.springframework.data.geo.Point as reading converter although it doesn't convert from a store-supported type! You might want to check your annotation setup at the converter implementation.
2020-09-01 14:10:38.503 WARN 99192 --- [ main] o.s.data.convert.CustomConversions : Registering converter from class org.springframework.data.elasticsearch.core.geo.GeoPoint to interface java.util.Map as writing converter although it doesn't convert to a store-supported type! You might want to check your annotation setup at the converter implementation.
2020-09-01 14:10:38.503 WARN 99192 --- [ main] o.s.data.convert.CustomConversions : Registering converter from interface java.util.Map to class org.springframework.data.elasticsearch.core.geo.GeoPoint as reading converter although it doesn't convert from a store-supported type! You might want to check your annotation setup at the converter implementation.
2020-09-01 14:10:38.604 INFO 99192 --- [ main] o.s.d.elasticsearch.support.VersionInfo : Version Spring Data Elasticsearch: 4.0.3.RELEASE
2020-09-01 14:10:38.604 INFO 99192 --- [ main] o.s.d.elasticsearch.support.VersionInfo : Version Elasticsearch Client in build: 7.6.2
2020-09-01 14:10:38.605 INFO 99192 --- [ main] o.s.d.elasticsearch.support.VersionInfo : Version Elasticsearch Client used: 7.6.2
2020-09-01 14:10:38.605 INFO 99192 --- [ main] o.s.d.elasticsearch.support.VersionInfo : Version Elasticsearch cluster: 6.8.4
2020-09-01 14:10:38.605 WARN 99192 --- [ main] o.s.d.elasticsearch.support.VersionInfo : Version mismatch in between Elasticsearch Client and Cluster: 7.6.2 - 6.8.4
2020-09-01 14:10:38.688 INFO 99192 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9898 (http) with context path ''
2020-09-01 14:10:38.698 INFO 99192 --- [ main] com.quan.sbrabbit.SbrabbitApplication : Started SbrabbitApplication in 16.941 seconds (JVM running for 22.495)
org.springframework.boot.SpringApplication@4a163575
监听到applicationStartedEvent
自定义事件:必须继承抽象类ApplicationEvent
public class QuanEvent extends ApplicationEvent { /**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public QuanEvent(String source) {
super(source);
System.out.println("事件 "+source);
}
}
自定义监听器:监听自己定义的事件
public class QuanListenerQuanEvent implements ApplicationListener<QuanEvent> {
@Override
public void onApplicationEvent(QuanEvent event) {
System.out.println("监听到QuanEvent"); }
}
在完成springboot启动事件ApplicationStaredEvent中发布事件:
public class QuanListenerStartedEvent implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
event.getApplicationContext().publishEvent(new QuanEvent("hello"));
}
}
最后加上监听器的配置:
在spring.factories追加:
,com.quan.sbrabbit.Listener.QuanListenerQuanEvent
运行结果:
也可以使用注解进行监听器的编写(这时候只需要将监听器加载到bean容器里面就行,)
使用注解@EventListener
@Component
public class QuanListenerQuanEvent {
@EventListener
public void onApplicationEvent(QuanEvent event) {
System.out.println("监听到QuanEvent"); }
}
监听事件的原理:
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event); }
监听器触发机制:
SpringApplication-run 方法
public ConfigurableApplicationContext run(String... args){
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
}
进入starting方法到SpringApplicationRunListener类
void starting() {
for (SpringApplicationRunListener listener : this.listeners) {
listener.starting();
}
}
遍历所有的SpringApplicationRunListener 再进入starting:来到EventPublishingRunListener类:
@Override
public void starting() {
this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
}
调用广播器发送 进入multicastEvent方法属于这个类:SimpleApplicationEventMulticaster
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
Executor executor = getTaskExecutor(); //获得线程池
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {//获取对当前event感兴趣的监听器列表
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
} 进入getApplicationListeners方法到类AbstractApplicationEventMulticaster
protected Collection<ApplicationListener<?>> getApplicationListeners(
ApplicationEvent event, ResolvableType eventType) { Object source = event.getSource();//获得事件来源 其实source就是SpringApplication
spring-boot-learning-监听事件的更多相关文章
- Spring boot实现监听Redis key失效事件实现和其它方式
需求: 处理订单过期自动取消,比如下单30分钟未支付自动更改订单状态 用户绑定隐私号码当订单结束取消绑定等 解决方案1: 可以利用redis自带的key自动过期机制,下单时将订单id写入redis,过 ...
- 【Redis系列】Spring boot实现监听Redis key失效事件
talk is cheap, show me the code. 一.开启Redis key过期提醒 方式二:修改配置文件 redis.conf # 默认 notify-keyspace-events ...
- spring boot实战(第二篇)事件监听
http://blog.csdn.net/liaokailin/article/details/48186331 前言 spring boot在启动过程中增加事件监听机制,为用户功能拓展提供极大的便利 ...
- spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情
<spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...
- 利用spring的ApplicationListener监听某一类事件的发生
1.ApplicationListener在使用过程中可以监听某一事件的发生,可以做出相应的处理,这个方式不常用,但是在特殊情况下面还是有用的. 2.导包pom.xml <project xml ...
- springboot13 发布和监听事件
spring中的事件驱动模型Event(也叫发布订阅模式),是观察者模式的一个典型的应用 好处:业务解耦,在不影响原来业务逻辑的情况下,加入其它业务 场景: app上线后已实现用户注册功能,现需要在用 ...
- zookeeper 监听事件 PathChildrenCacheListener
zookeeper 监听事件 PathChildrenCacheListener PathChildrenCacheListener一次父节点注册,监听每次子节点操作,不监听自身和查询. 1.测试类: ...
- zookeeper 监听事件 NodeCacheListener
zookeeper 监听事件 NodeCacheListener NodeCacheListener一次注册,每次监听,但是监听不到操作类型,不知道是增加?删除?还是修改? 1.测试类: packag ...
- zookeeper 监听事件 CuratorWatcher
zookeeper 监听事件 CuratorWatcher CuratorWatcher一次注册只监听一次,不监听查询. 1.监听测试类 package com.qy.learn.zk.curator ...
- Redis集群环境下的键值空间监听事件实现方案
一直想记录工作中遇到的问题和解决的方法,奈何没有找到一方乐土,最近经常反思,是否需要记录平时的点滴,后台还是决定下定决心记录一些,以便以后用到的时候找不着,实现这样的一个功能主要也是业务所需要的. 需 ...
随机推荐
- IDEA使用JDBC链接MySql(java编程)
1.在Maven的pom.xml文件中引入MySql的驱动 <dependency> <groupId>mysql</groupId> <artifactId ...
- jmeter参数化文件路径问题
问题 win下做好的带参数化文件的脚本,放到linux下运行,由于参数化文件路径不正确,导致脚本运行失败,如果解决这个问题呢? 方案一:参数化路径 比如,参数化文件我放到jmeter的bin目录下,参 ...
- 详解用OpenCV绘制各类几何图形
摘要:本文详细介绍了OpenCV绘制几何图形的方法,利用cv2.line().v2.circle().cv2.rectangle().cv2.ellipse().cv2.polylines().cv2 ...
- 支持 dd 命令的简单的 GUI 实用程序
Kindd-支持 dd 命令的简单的 GUI 实用程序 "Kindd",一个属于dd 命令的图形化前端.它是自由开源的.用 Qt Quick 所写的工具.总的来说,这个工具对那些对 ...
- Windows原理深入学习系列-访问控制列表
这是[信安成长计划]的第 19 篇文章 0x00 目录 0x01 介绍 0x02 DACL 0x03 创建DACL 0x04 文件读取测试 0x05 进程注入测试 0x06 原理分析 Win10_x6 ...
- 微服务从代码到k8s部署应有尽有系列(九、事务精讲)
我们用一个系列来讲解从需求到上线.从代码到k8s部署.从日志到监控等各个方面的微服务完整实践. 整个项目使用了go-zero开发的微服务,基本包含了go-zero以及相关go-zero作者开发的一些中 ...
- 人工智能之深度学习-初始环境搭建(安装Anaconda3和TensorFlow2步骤详解)
前言: 本篇文章主要讲解的是在学习人工智能之深度学习时所学到的知识和需要的环境配置(安装Anaconda3和TensorFlow2步骤详解),以及个人的心得体会,汇集成本篇文章,作为自己深度学习的总结 ...
- Scrapy(六):Spider
总结自:Spiders - Scrapy 2.5.0 documentation Spider 1.综述 ①在回调函数Parse及其他自写的回调函数中,必须返回Item对象.Request对象.或前两 ...
- prometheus-数据展示之grafana部署和数据源配置
1.监控pods . prometheus再部署以后,会自带cAdvisor.结果如下: 2.K8S集群状态监控.需要使用kube-state-metrics插件.部署以后 kubernetes. ...
- JAVA Object类方法
目录 Object类详解 一.==和equals的对比 1.1 ==是一个比较运算符 1.2 equals方法 二.hashCode方法 三.toString方法 四.finalize方法 Objec ...