spring boot之SpringApplication 事件监听
spring application listener
在 spring 框架中,有多种事件, 这些时间会在不同的运行时刻发布,来通知监听者。本文仅仅介绍 SpringApplicationEvent 的事件的监听。
事件类型
| EventType | 发布时间 |
|---|---|
| ApplicationContextInitializedEvent | 在 SpringApplication正在启动, ApplicationContext 已经准备好了,ApplicationContextInitializers 被调用, bean definitions 被加载之前 |
| ApplicationStartingEvent | 在一次启动之前发布 |
| ApplicationEnvironmentPreparedEvent | 在 Environment 准备好之后,会有 context 去使用这一 Environment, 会在 context 创建之前发出 |
| ApplicationPreparedEvent | 会在 bean definitions 加载之后,refresh 之前发布 |
| ApplicationStartedEvent | context 更新之后,任何应用或命令行启动调用之前 |
| ApplicationReadyEvent | 任何应用或命令行启动调用之后发布,说明应用已经可以被请求了 |
| ApplicationFailedEvent | 启动发生有异常时发步 |
如何监听
监听器需要使用 org.springframework.context.ApplicationListener 这个接口的实例, 其声明如下:
@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.addListeners(…) 或 SpringApplicationBuilder.listeners(…) 来添加监听器。也可以在 META-INF/spring.factories 文件中配置:org.springframework.context.ApplicationListener=com.example.project.MyListener。
例子:
public class StartingEventListener implements ApplicationListener<ApplicationStartingEvent> {
@Override
public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
System.out.println("called own starting listener");
System.out.println(applicationStartingEvent.getClass());
}
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args){
SpringApplication application = new SpringApplication(DemoApplication.class);
application.addListeners(new StartingEventListener());
application.run(args);
}
}
终端运行 jar 包:
$ java -jar build/libs/springlisteners-0.0.1-SNAPSHOT.jar called own starting listener class org.springframework.boot.context.event.ApplicationStartingEvent . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.3.RELEASE)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Mybatis返回int或者Integer类型报错的解决办法
这篇文章主要介绍了Mybatis返回int或者Integer类型报错的解决办法,非常不错,具有参考借鉴价值,需要的朋友可以参考下2016-12-12
springboot整合Quartz实现动态配置定时任务的方法
本篇文章主要介绍了springboot整合Quartz实现动态配置定时任务的方法,非常具有实用价值,需要的朋友可以参考下2017-10-10
一篇文章带你入门Springboot整合微信登录与微信支付(附源码)
微信支付是腾讯公司的支付业务品牌,微信支付商户平台支持线下场所、公众号、小程序、PC网站、APP、企业微信等经营场景快速接入微信支付。这里一篇文章带你入门!2021-06-06
使用Jacoco获取 Java 程序的代码执行覆盖率的步骤详解
这篇文章主要介绍了使用Jacoco获取 Java 程序的代码执行覆盖率的步骤详解,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下2021-03-03
IDEA中springboot的热加载thymeleaf静态html页面的方法
这篇文章主要介绍了IDEA中springboot的热加载thymeleaf静态html页面的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-07-07


最新评论