spring boot在启动过程中增加事件监听机制,为用户功能拓展提供极大的便利,sptingboot支持的事件类型有以下五种:

  • ApplicationStartingEvent
  • ApplicationFailedEvent
  • ApplicationPreparedEvent
  • ApplicationReadyEvent
  • ApplicationEnvironmentPreparedEvent

实现监听步骤

  1.监听类实现ApplicationListener接口

  2.将监听类添加到SpringApplication实例中

ApplicationStartingEvent

  ApplicationStartingEvent:springboot启动开始的时候执行的事件,在该事件中可以获取到SpringApplication对象,可做一些执行前的设置。

package com.ysl.listener;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener; /**
* springboot启动监听类
*/
public class MyApplicationStartingEventListener implements ApplicationListener<ApplicationStartingEvent>{ @Override
public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
SpringApplication application = applicationStartingEvent.getSpringApplication();
application.setBannerMode(Banner.Mode.OFF);
System.out.println("--------- execute MyApplicationStartingEventListener----------");
} }
package com.ysl;

import com.ysl.listener.MyApplicationStartingEventListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application { public static void main(String[] args){
SpringApplication app =new SpringApplication(Application.class);
app.addListeners(new MyApplicationStartingEventListener());
app.run(args);
}
}

执行结果如下:

--------- execute MyApplicationStartingEventListener----------
-- ::58.027 INFO --- [ main] com.ysl.Application : Starting Application on master with PID (/home/workspace/springboottest/target/classes started by ysl in /home/workspace/springboottest)
-- ::58.032 INFO --- [ main] com.ysl.Application : No active profile set, falling back to default profiles: default
-- ::58.182 INFO --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f32bf7: startup date [Sat Mar :: CST ]; root of context hierarchy

ApplicationEnvironmentPreparedEvent

  ApplicationEnvironmentPreparedEvent:spring boot 对应Enviroment已经准备完毕,但此时上下文context还没有创建。在该监听中获取到ConfigurableEnvironment后可以对配置信息做操作,例如:修改默认的配置信息,增加额外的配置信息等等。

package com.ysl.listener;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource; import java.util.Iterator; /**
* spring boot 配置环境事件监听
*/
public class MyApplicationEnvironmentPreparedEventListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>{ @Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
MutablePropertySources maps = environment.getPropertySources();
if(maps != null){
Iterator<PropertySource<?>> its = maps.iterator();
while(its.hasNext()){
PropertySource<?> ps =its.next();
System.out.print(ps.getName() + "-----");
System.out.print(ps.getSource() + "-----");
System.out.println(ps.getClass() + "-----");
}
}
} }

运行结果

--------- execute MyApplicationStartingEventListener----------
servletConfigInitParams-----java.lang.Object@1ca2dfa-----class org.springframework.core.env.PropertySource$StubPropertySource-----
servletContextInitParams-----java.lang.Object@153f538-----class org.springframework.core.env.PropertySource$StubPropertySource-----

ApplicationPreparedEvent

  ApplicationPreparedEvent:spring boot上下文context创建完成,但此时spring中的bean是没有完全加载完成的。在获取完上下文后,可以将上下文传递出去做一些额外的操作。值得注意的是:在该监听器中是无法获取自定义bean并进行操作的。

package com.ysl.listener;

import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext; public class MyApplicationPreparedEventListener implements ApplicationListener<ApplicationPreparedEvent>{ @Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
ConfigurableApplicationContext context = event.getApplicationContext();
passContextInfo(context);
} /**
* 传递上下文
* @param cac
*/
private void passContextInfo(ApplicationContext cac) {
//dosomething()
}
}

ApplicationFailedEvent

  ApplicationFailedEvent:spring boot启动异常时执行事件,在异常发生时,最好是添加虚拟机对应的钩子进行资源的回收与释放,能友善的处理异常信息

package com.ysl.listener;

import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener; public class MyApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> { @Override
public void onApplicationEvent(ApplicationFailedEvent applicationFailedEvent) {
Throwable t = applicationFailedEvent.getException();
//do something
} }

ApplicationReadyEvent

  ApplicationReadyEvent:springboot 加载完成时候执行的事件

package com.ysl.listener;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener; public class MyApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent>{
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
applicationReadyEvent.getApplicationContext();
System.out.println("start ready");
}
}

运行结果  

-- ::54.453  INFO  --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
-- ::54.513 INFO --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): (http)
start ready
-- ::54.517 INFO --- [ main] com.ysl.Application : Started Application in 4.718 seconds (JVM running for 5.264)
												

SpringBoot入门之事件监听的更多相关文章

  1. SpringBoot框架(6)--事件监听

    一.场景:类与类之间的消息通信,例如创建一个对象前后做拦截,日志等等相应的事件处理. 二.事件监听步骤 (1)自定义事件继承ApplicationEvent抽象类 (2)自定义事件监听器,一般实现Ap ...

  2. SpringBoot事件监听机制及观察者模式/发布订阅模式

    目录 本篇要点 什么是观察者模式? 发布订阅模式是什么? Spring事件监听机制概述 SpringBoot事件监听 定义注册事件 注解方式 @EventListener定义监听器 实现Applica ...

  3. springboot 中事件监听模型的一种实现

    目录 定义事件本身 定义事件源 定义监听者 一.需要实现 ApplicationListener 二.使用 @EventListener 注解 测试 项目结构 前言: 事件监听模型是一种常用的设计模式 ...

  4. SpringBoot Application事件监听

    SpringBoot Application共支持6种事件监听,按顺序分别是: ApplicationStartingEvent:在Spring最开始启动的时候触发 ApplicationEnviro ...

  5. SpringBoot事件监听机制源码分析(上) SpringBoot源码(九)

    SpringBoot中文注释项目Github地址: https://github.com/yuanmabiji/spring-boot-2.1.0.RELEASE 本篇接 SpringApplicat ...

  6. springBoot高级:自动配置分析,事件监听,启动流程分析,监控,部署

    知识点梳理 课堂讲义 02-SpringBoot自动配置-@Conditional使用 Condition是Spring4.0后引入的条件化配置接口,通过实现Condition接口可以完成有条件的加载 ...

  7. SpringBoot的事件监听

    事件监听的流程分为三步:1.自定义事件,一般是继承ApplicationEvent抽象类.2.定义事件监听器,一般是实现ApplicationListener接口.3.a.启动的时候,需要将监听器加入 ...

  8. 4.pygame快速入门-事件监听

    事件event:游戏启动后,用户针对游戏的所有操作 监听:在游戏循环中,判断用户的具体操作 pygame中通过pygame.event.get()可以获得当前用户所做动作的事件列表   事件监听 wh ...

  9. Java中用得比较顺手的事件监听

    第一次听说监听是三年前,做一个webGIS的项目,当时对Listener的印象就是个"监视器",监视着界面的一举一动,一有动静就触发对应的响应. 一.概述 通过对界面的某一或某些操 ...

随机推荐

  1. 移动端web及app设计尺寸

    转载 2017年07月27日 22:48:16 984 移动端高清.多屏适配方案 背景 开发移动端H5页面 面对不同分辨率的手机 面对不同屏幕尺寸的手机 视觉稿 在前端开发之前,视觉MM会给我们一个p ...

  2. seo工具

    http://tool.seowhy.com/ 一.关键词查词类工具:可以查询出更多目标客户可能搜索的词语 1.百度指数:http://index.baidu.com/ 这个工具是使用人数最多的 2. ...

  3. TextView等组件的LayoutParams不能随便用,不然组件不显示

    TableLayout.LayoutParams lpRow = new TableLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTEN ...

  4. 为什么const对象只能调用const成员函数,而不能调用非const成员函数?

    在c++中,我们可以用const来定义一个const对象,const对象是不可以调用类中的非const成员函数,这是为什么呢?下面是我总结的一些原理. 假设有一个类,名字为test代码如下: clas ...

  5. python数据类型2

    一 文件格式补充 在python3中,除字符串外,所有数据类型在内存中的编码格式都是utf-8,而字符串在内存中的格式是Unicode的格式. 由于Unicode的格式无法存入硬盘中,所以这里还有一种 ...

  6. 2018.08.17 洛谷[POI2010]GRA-The Minima Game(线性dp)

    传送门 短代码神奇dp. 自己yy的思路居然1A了好高兴啊! 不难想到每个人选择的时候一定是取连续的最大的那一段数,自然需要先排序. 然后可以用dp[i]表示当前最大数是a[i]的时候先手可以获得的最 ...

  7. python类的继承-1

    #!/usr/bin/python3 #类定义 class people: #定义基本属性 name = '' age = 0 #定义私有属性,私有属性在类外部无法直接进行访问 __weight = ...

  8. addEvent兼容版

    function addEvent(elem,type,handle){ if (elem.addEventlistener) { elem.addEventlistener(type,handle, ...

  9. BSD Socket 通信

    Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain ...

  10. (字典树)How many--hdu--2609

    http://acm.hdu.edu.cn/showproblem.php?pid=2609 How many Time Limit: 2000/1000 MS (Java/Others)    Me ...