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-监听事件的更多相关文章

  1. Spring boot实现监听Redis key失效事件实现和其它方式

    需求: 处理订单过期自动取消,比如下单30分钟未支付自动更改订单状态 用户绑定隐私号码当订单结束取消绑定等 解决方案1: 可以利用redis自带的key自动过期机制,下单时将订单id写入redis,过 ...

  2. 【Redis系列】Spring boot实现监听Redis key失效事件

    talk is cheap, show me the code. 一.开启Redis key过期提醒 方式二:修改配置文件 redis.conf # 默认 notify-keyspace-events ...

  3. spring boot实战(第二篇)事件监听

    http://blog.csdn.net/liaokailin/article/details/48186331 前言 spring boot在启动过程中增加事件监听机制,为用户功能拓展提供极大的便利 ...

  4. spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情

    <spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...

  5. 利用spring的ApplicationListener监听某一类事件的发生

    1.ApplicationListener在使用过程中可以监听某一事件的发生,可以做出相应的处理,这个方式不常用,但是在特殊情况下面还是有用的. 2.导包pom.xml <project xml ...

  6. springboot13 发布和监听事件

    spring中的事件驱动模型Event(也叫发布订阅模式),是观察者模式的一个典型的应用 好处:业务解耦,在不影响原来业务逻辑的情况下,加入其它业务 场景: app上线后已实现用户注册功能,现需要在用 ...

  7. zookeeper 监听事件 PathChildrenCacheListener

    zookeeper 监听事件 PathChildrenCacheListener PathChildrenCacheListener一次父节点注册,监听每次子节点操作,不监听自身和查询. 1.测试类: ...

  8. zookeeper 监听事件 NodeCacheListener

    zookeeper 监听事件 NodeCacheListener NodeCacheListener一次注册,每次监听,但是监听不到操作类型,不知道是增加?删除?还是修改? 1.测试类: packag ...

  9. zookeeper 监听事件 CuratorWatcher

    zookeeper 监听事件 CuratorWatcher CuratorWatcher一次注册只监听一次,不监听查询. 1.监听测试类 package com.qy.learn.zk.curator ...

  10. Redis集群环境下的键值空间监听事件实现方案

    一直想记录工作中遇到的问题和解决的方法,奈何没有找到一方乐土,最近经常反思,是否需要记录平时的点滴,后台还是决定下定决心记录一些,以便以后用到的时候找不着,实现这样的一个功能主要也是业务所需要的. 需 ...

随机推荐

  1. IDEA如何快速生成get和set方法

    方法一:1.鼠标右击"Generate"2.点击"Getter and Setter",3.将定义的字段全部选中,点击OK.方法二:使用alt+insert 快 ...

  2. bugku ctf 杂项 旋转跳跃 (熟悉的声音中貌似又隐藏着啥,key:syclovergeek)

    做这道题之前先给出工具   MP3Stego 下载地址 链接:https://pan.baidu.com/s/1W2mmGJcrm570EdJ6o7jD7g  提取码:1h1b 题目下载加压后 是一个 ...

  3. RHEL6搭建网络yum源仓库

    RHEL的更新包只对注册用户生效,所以需要自己手动改成Centos的更新包 一.查看rhel本身的yum安装包 rpm -qa | grep yum 二.卸载这些软件包 rpm -qa | grep ...

  4. 【C# .Net GC】清除非托管类型(Finalize终结器、dispose模式以及safeHandler)

    总结 1.一般要获取一个内核对象的引用,最好用SafeHandle来引用它,这个类可以帮你管理引用计数,而且用它引用内核对象,代码更健壮 2.托管中生成并引用非托管,一但非托管和托管中的引用断开(托管 ...

  5. weblogic threadpool has stuck threads引发内存溢出

    转至:https://blog.csdn.net/wyx713510713/article/details/12705221?utm_source=copy 最近项目老是出问题,weblogic的no ...

  6. WIN10:显示隐藏文件夹

    AppData是默认隐藏文件夹,可以通过工具栏显示隐藏项目显示

  7. IDEA 快捷键和字体设置

    IDEA的使用 一.IDEA 目录 IDEA的使用 一.IDEA 设置字体 文本字体设置 窗口字体设置 二.IDEA建立项目 三.IDEA快捷键 设置字体 点击File->Settings 文本 ...

  8. Java 将XML转为PDF

    可扩展标记语言(XML)文件是一种标准的文本文件,它使用特定的标记来描述文档的结构以及其他特性.通过将XML转换为PDF,能够便于文件传输及共享.本文,将介绍通过Java代码来实现该格式转换的方法. ...

  9. tp5 商品模型的添加展示

    路由 //商品模型展示的路由 Route::get('type','/pyg/good/listType'); //将type_id传送至/pyg/good/addType的路由 Route::get ...

  10. [树]LeetCode589 N叉树的前序遍历

    LeetCode N叉树的前序遍历 前言:树的前中后序遍历已经是很经典的题目的,要么递归要么迭代,不过还是比较习惯于递归的写法 TITLE 给定一个 n 叉树的根节点 root ,返回 其节点值的 前 ...