springboot源码分析16-spring boot监听器使用

简介: 摘要:spring boot提供了一系列的监听器,方便我们开发人员使用和扩展。本文咱们详细讲解一下spring boot中的监听器。spring boot中支持的事件类型定在org.

摘要:spring boot提供了一系列的监听器,方便我们开发人员使用和扩展。

本文咱们详细讲解一下spring boot中的监听器。

spring boot中支持的事件类型定在org.springframework.boot.context.event包中,目前支持的事件类型有如下6种:

ApplicationFailedEvent

ApplicationPreparedEvent

ApplicationReadyEvent

ApplicationStartedEventSpringboot2.x版本已修改为ApplicationStartingEvent

SpringApplicationEvent

ApplicationEnvironmentPreparedEvent

1.1.  监听器的使用

第一:首先定义一个自己使用的监听器类并实现ApplicationListener接口。

第二:通过SpringApplication类中的addListeners方法将自定义的监听器注册进去。

1.1.1.  ApplicationFailedEvent

ApplicationFailedEvent:该事件为spring boot启动失败时的操作。

/**

* spring boot 启动的时候出现异常事件

* @author www.shareniu.com

*

*/

public class ShareniuApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> {

@Override

public void onApplicationEvent(ApplicationFailedEvent event) {

System.out.println("--------------:ShareniuApplicationFailedEventListener");

Throwable exception = event.getException();

System.out.println(exception);

}

}

可以通过ApplicationFailedEvent 获取Throwable实例对象获取异常信息并处理。

1.1.2.  ApplicationPreparedEvent

ApplicationPreparedEvent:上下文准备事件。

上下文context已经准备完毕 ,可以通过ApplicationPreparedEvent获取到ConfigurableApplicationContext实例对象。ConfigurableApplicationContext类继承ApplicationContext类,但需要注意这个时候spring容器中的bean还没有被完全的加载,因此如果通过ConfigurableApplicationContext获取bean会报错的。比如报错:

Exception in thread "main" java.lang.IllegalStateException: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@69b0fd6f has not been refreshed yet

获取到上下文之后,可以将其注入到其他类中,毕竟ConfigurableApplicationContext为引用类型。

public class ShareniuApplicationPreparedEventListener implements ApplicationListener<ApplicationPreparedEvent> {

@Override

public void onApplicationEvent(ApplicationPreparedEvent event) {

System.out.println("###############"+"ShareniuApplicationPreparedEventListener");

ConfigurableApplicationContext applicationContext = event.getApplicationContext();

//如果执行下面代码则报错

//ShareniuDemo shareniuDemo = applicationContext.getBean(ShareniuDemo.class);

//System.out.println(shareniuDemo);

}

}

1.1.3.  ApplicationReadyEvent

ApplicationReadyEvent:上下文已经准备ok

这个时候就可以通过ApplicationReadyEvent获取ConfigurableApplicationContext,然后通过ConfigurableApplicationContext 获取bean的信息。

public class ShareniuApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

@Override

public void onApplicationEvent(ApplicationReadyEvent event) {

System.out.println("--------------------:ShareniuApplicationReadyEventListener");

ConfigurableApplicationContext applicationContext = event.getApplicationContext();

    //ShareniuDemo可以根基自身情况进行测试

ShareniuDemo shareniuDemo = applicationContext.getBean(ShareniuDemo.class);

}

}

1.1.4.  ApplicationStartedEvent

ApplicationStartedEventspring boot 启动监听类。该类在SpringBoot2.x版本中已经废弃,修改为了最新的类,类名是ApplicationStartingEvent。这个事件是第一个产生的。

可以在SpringApplication启动之前做一些手脚,比如修改SpringApplication实例对象中的属性值。

public class ShareniuApplicationStartedEventListener  implements ApplicationListener<ApplicationStartedEvent>{

@Override

public void onApplicationEvent(ApplicationStartedEvent event) {

SpringApplication springApplication = event.getSpringApplication();

springApplication.setShowBanner(false);

System.out.println("##############################ShareniuApplicationStartedEventListener");

}

}

1.1.5.  SpringApplicationEvent

SpringApplicationEvent:获取SpringApplication

public class ShareniuSpringApplicationEventListener implements ApplicationListener<SpringApplicationEvent> {

@Override

public void onApplicationEvent(SpringApplicationEvent event) {

System.out.println("-----------------------:ShareniuSpringApplicationEventListener");

SpringApplication springApplication = event.getSpringApplication();

System.out.println("###############"+springApplication);

}

}

1.1.6.  ApplicationEnvironmentPreparedEvent

ApplicationEnvironmentPreparedEvent:环境事先准备,spring boot中的环境已经准备ok

可以通过ApplicationEnvironmentPreparedEvent获取到SpringApplicationConfigurableEnvironment等等信息, 可以通过ConfigurableEnvironment实例对象来修改以及获取默认的环境信息。

public class ShasreniuApplicationEnvironmentPreparedEventListener  implements ApplicationListener<ApplicationEnvironmentPreparedEvent>{

@Override

public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

System.out.println("###############"+"ShasreniuApplicationEnvironmentPreparedEventListener");

SpringApplication springApplication = event.getSpringApplication();

ConfigurableEnvironment environment = event.getEnvironment();

long timestamp = event.getTimestamp();

Object source = event.getSource();

System.out.println("########################"+springApplication);

System.out.println("########################"+environment);

System.out.println("########################"+timestamp);

System.out.println("########################"+source);

MutablePropertySources propertySources = environment.getPropertySources();

if (propertySources!=null) {

Iterator<PropertySource<?>> iterator = propertySources.iterator();

while (iterator.hasNext()) {

PropertySource<?> propertySource = (PropertySource<?>) iterator.next();

System.out.println("##############:propertySource"+propertySource);

}

}

 }

}

1.2.  监听器注册

@RestController

@SpringBootApplication()

public class Application {

@RequestMapping("/")

String index() {

return "xxxxxxxxxxxxx";

}

public static void main(String[] args) {

SpringApplication springApplication = new SpringApplication(Application.class);

springApplication.addListeners(new ShareniuApplicationStartedEventListener());

springApplication.addListeners(new ShasreniuApplicationEnvironmentPreparedEventListener());

springApplication.addListeners(new ShareniuApplicationPreparedEventListener());

springApplication.addListeners(new ShareniuApplicationFailedEventListener());

springApplication.addListeners(new ShareniuApplicationReadyEventListener());

springApplication.addListeners(new ShareniuSpringApplicationEventListener());

springApplication.run(args);

}

}


欢迎关注我的微信公众号,第一时间获得博客更新提醒,以及更多成体系的Java相关原创技术干货。 
扫一扫下方二维码或者长按识别二维码,即可关注。
 


相关文章
|
2月前
|
前端开发 JavaScript Java
【实操】SpringBoot监听Iphone15邮件提醒,Selenium+Python自动化抢购脚本
本文介绍了一个结合SpringBoot和Python的实用功能,旨在监控iPhone 15的库存状态并通过邮件提醒用户。系统采用SpringBoot监听苹果官网API,解析JSON数据判断是否有货,并展示最近的库存记录。此外,还能自动触发Selenium+Python脚本实现自动化购买。文中详细介绍了技术栈、接口分析、邮件配置及自动化脚本的设置方法。该项目不仅适用于熟悉后端开发的人员,也适合回顾Layui和Jquery等前端技术。
43 0
【实操】SpringBoot监听Iphone15邮件提醒,Selenium+Python自动化抢购脚本
|
22天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
2月前
|
缓存 NoSQL Java
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
Spring Cache 是 Spring 提供的简易缓存方案,支持本地与 Redis 缓存。通过添加 `spring-boot-starter-data-redis` 和 `spring-boot-starter-cache` 依赖,并使用 `@EnableCaching` 开启缓存功能。JetCache 由阿里开源,功能更丰富,支持多级缓存和异步 API,通过引入 `jetcache-starter-redis` 依赖并配置 YAML 文件启用。Layering Cache 则提供分层缓存机制,需引入 `layering-cache-starter` 依赖并使用特定注解实现缓存逻辑。
355 1
SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)
|
2月前
|
Java 微服务 Spring
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
文章介绍了如何利用Spring Cloud Alibaba快速构建大型电商系统的分布式微服务,包括服务限流降级等主要功能的实现,并通过注解和配置简化了Spring Cloud应用的接入和搭建过程。
SpringBoot+Vue+Spring Cloud Alibaba 实现大型电商系统【分布式微服务实现】
|
2月前
|
安全 Java 数据安全/隐私保护
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
本文介绍了一个基于SpringBoot、Spring Security和JPA开发的校园图书管理系统,包括系统的核心控制器`LoginController`的代码实现,该控制器处理用户登录、注销、密码更新、角色管理等功能,并提供了系统初始化测试数据的方法。
36 0
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
|
2月前
|
安全 Java 数据库
|
2月前
|
JSON 安全 Java
|
3月前
|
Java Spring 容器
Spring Boot 启动源码解析结合Spring Bean生命周期分析
Spring Boot 启动源码解析结合Spring Bean生命周期分析
87 11
|
2月前
|
缓存 Java 数据库
Spring Boot中使用监听器
系统的介绍了监听器原理,以及在 Spring Boot 中如何使用监听器,列举了监听器的三个常用的案例,有很好的实战意义。最后讲解了项目中如何自定义事件和监听器,并结合微服务中常见的场景,给出具体的代码模型,均能运用到实际项目中去,希望读者认真消化。
|
2月前
|
Java Spring
【Azure 事件中心】Spring Boot 集成 Event Hub(azure-spring-cloud-stream-binder-eventhubs)指定Partition Key有异常消息
【Azure 事件中心】Spring Boot 集成 Event Hub(azure-spring-cloud-stream-binder-eventhubs)指定Partition Key有异常消息
下一篇
无影云桌面