springboot源码-自定义监听事件

springboot源码-自定义监听事件

springboot中默认监听器

监听器监听事件说明
ClearCachesApplicationListenerContextRefreshedEvent当触发ContextRefreshedEvent事件会清空应用的缓存
ParentContextCloserApplicationListenerParentContextAvailableEvent触发ParentContextAvailableEvent事件会完成父容器关闭的监听器
CloudFoundryVcapEnvironmentPostProcessorApplicationPreparedEvent判断环境中是否存在VCAP_APPLICATION或者VCAP_SERVICES。如果有就添加Cloud Foundry的配置;没有就不执行任何操作。
FileEncodingApplicationListenerApplicationEnvironmentPreparedEvent文件编码的监听器
AnsiOutputApplicationListenerApplicationEnvironmentPreparedEvent根据 spring.output.ansi.enabled参数配置 AnsiOutput
ConfigFileApplicationListenerApplicationEnvironmentPreparedEvent <br>ApplicationPreparedEvent完成相关属性文件的加载,application.properties
application.yml
前面源码内容详细讲解过
DelegatingApplicationListenerApplicationEnvironmentPreparedEvent监听到事件后转发给环境变量 context.listener.classes指定的那些事件监听器
ClasspathLoggingApplicationListenerApplicationEnvironmentPreparedEvent <br>ApplicationFailedEvent一个SmartApplicationListener,对环境就绪事件ApplicationEnvironmentPreparedEvent/应用失败事件ApplicationFailedEvent做出响应,往日志DEBUG级别输出TCCL(thread context class loader)的classpath。
LoggingApplicationListenerApplicationStartingEvent <br>ApplicationEnvironmentPreparedEvent <br>ApplicationPreparedEvent <br>ContextClosedEvent <br>ApplicationFailedEvent配置 LoggingSystem。使用 logging.config环境变量指定的配置或者缺省配置
LiquibaseServiceLocatorApplicationListenerApplicationStartingEvent使用一个可以和Spring Boot可执行jar包配合工作的版本替换liquibase ServiceLocator
BackgroundPreinitializerApplicationStartingEvent <br>ApplicationReadyEvent <br>ApplicationFailedEvent尽早触发一些耗时的初始化任务,使用一个后台线程

SpringBoot中的事件类型

ApplicationStartingEvent容器启动的事件
ApplicationEnvironmentPreparedEvent应用处理环境变量相关的事件
ApplicationContextInitializedEvent容器初始化的事件
ApplicationPreparedEvent应用准备的事件
ApplicationFailedEvent应用启动出错的事件
事件说明
ApplicationStartedEvent应用Started状态事件
ApplicationReadyEvent应用准备就绪的事件

源码查看监听器

SpringApplication.java

image-20220723234036101

自定义监听器

监听所有事件

MyApplicationListener.java

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
 * 自定义监听器
 * 1.实现 ApplicationListener 接口 , 在泛型中实行要监听的事件类型
 *    如果事件类型是 ApplicationEvent , 则表示监听所有事件
 *  2. 需要吧监听器在 spring.factories 文件中红配置   
 */
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        System.out.println("MyApplicationListener  -----> " + applicationEvent);
    }
}

监听特定事件

MyStartApplicationListener.java

/**
 * 自定义监听器
 * 1.实现 ApplicationListener 接口 , 在泛型中实行要监听的事件类型
 *    如果事件类型是 ApplicationEvent , 则表示监听所有事件
 *    如果是具体的某个类型 , 比如 ApplicationStartingEvent , 则表示监听容器开始的事件
 *  2. 需要吧监听器在 spring.factories 文件中红配置   
 */
public class MyStartApplicationListener implements ApplicationListener<ApplicationStartingEvent> {

    // 触发相关事件的回调方法
    @Override
    public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
        System.out.println("MyStartApplicationListener --->" + applicationStartingEvent);
    }
}

自定义事件

MyEvent.java

import org.springframework.context.ApplicationEvent;

public class MyEvent extends ApplicationEvent {
    public MyEvent(Object source) {
        super(source);
        System.out.println("MyEvent -----> 自定义事件");
    }
}

MyListener.java

import org.springframework.context.ApplicationListener;

public class MyListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent myEvent) {
        System.out.println("MyListener ---->"+myEvent.getSource());
    }
}

测试

新建 META-INF/spring.factories 文件
org.springframework.context.ApplicationListener=\
com.example.controller.listener.MyApplicationListener,\
com.example.controller.listener.MyStartApplicationListener,\
com.example.controller.listener.MyListener
触发自定义事件

HelloController.java

@RestController
public class HelloController {

    @Autowired
    private ApplicationContext ac;
    @GetMapping("/")
    public String hello() {
        //发布事件
        ac.publishEvent(new MyEvent(new Object()));
        return "";
    }

}
控制台打印

MyApplicationListener -----> org.springframework.boot.context.event.ApplicationStartingEvent[source=org.springframework.boot.SpringApplication@5702b3b1]
MyStartApplicationListener —>org.springframework.boot.context.event.ApplicationStartingEvent[source=org.springframework.boot.SpringApplication@5702b3b1]
MyApplicationListener -----> org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent[source=org.springframework.boot.SpringApplication@5702b3b1]

. ____ _ __ _ _
/\ / __ _ () __ __ _ \ \ \
( ( )_
_ | '_ | '| | ’ / ` | \ \ \
\/ )| |)| | | | | || (| | ) ) ) )
’ |
| .__|| ||| |_, | / / / /
=========|
|==============|/=////
:: Spring Boot :: (v2.3.7.RELEASE)

MyApplicationListener -----> org.springframework.boot.context.event.ApplicationContextInitializedEvent[source=org.springframework.boot.SpringApplication@5702b3b1]
2022-07-23 23:48:09.815 INFO 13164 — [ main] com.example.SpringbootDemoApplication : Starting SpringbootDemoApplication on MSI with PID 13164 (D:\git-res\tmp\springboot-demo\target\classes started by - in D:\git-res\tmp\springboot-demo)
2022-07-23 23:48:09.817 INFO 13164 — [ main] com.example.SpringbootDemoApplication : No active profile set, falling back to default profiles: default
MyApplicationListener -----> org.springframework.boot.context.event.ApplicationPreparedEvent[source=org.springframework.boot.SpringApplication@5702b3b1]
2022-07-23 23:48:10.202 INFO 13164 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-07-23 23:48:10.206 INFO 13164 — [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-07-23 23:48:10.206 INFO 13164 — [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2022-07-23 23:48:10.240 INFO 13164 — [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-07-23 23:48:10.240 INFO 13164 — [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 402 ms
2022-07-23 23:48:10.310 INFO 13164 — [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService ‘applicationTaskExecutor’
2022-07-23 23:48:10.383 INFO 13164 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ‘’
MyApplicationListener -----> org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent[source=org.springframework.boot.web.embedded.tomcat.TomcatWebServer@6c000e0c]
MyApplicationListener -----> org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@192d43ce, started on Sat Jul 23 23:48:09 GMT+08:00 2022]
2022-07-23 23:48:10.389 INFO 13164 — [ main] com.example.SpringbootDemoApplication : Started SpringbootDemoApplication in 0.718 seconds (JVM running for 1.092)
MyApplicationListener -----> org.springframework.boot.context.event.ApplicationStartedEvent[source=org.springframework.boot.SpringApplication@5702b3b1]
MyApplicationListener -----> org.springframework.boot.availability.AvailabilityChangeEvent[source=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@192d43ce, started on Sat Jul 23 23:48:09 GMT+08:00 2022]
MyApplicationListener -----> org.springframework.boot.context.event.ApplicationReadyEvent[source=org.springframework.boot.SpringApplication@5702b3b1]
MyApplicationListener -----> org.springframework.boot.availability.AvailabilityChangeEvent[source=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@192d43ce, started on Sat Jul 23 23:48:09 GMT+08:00 2022]

ngeEvent[source=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@192d43ce, started on Sat Jul 23 23:48:09 GMT+08:00 2022]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值