http://blog.csdn.net/liaokailin/article/details/48186331

前言

spring boot在启动过程中增加事件监听机制,为用户功能拓展提供极大的便利。

支持的事件类型四种

ApplicationStartedEvent

ApplicationEnvironmentPreparedEvent

ApplicationPreparedEvent

ApplicationFailedEvent

实现监听步骤:

1.监听类实现ApplicationListener接口 
2.将监听类添加到SpringApplication实例

ApplicationStartedEvent

ApplicationStartedEvent:spring boot启动开始时执行的事件

创建对应的监听类 MyApplicationStartedEventListener.java

package com.lkl.springboot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener; /**
* spring boot 启动监听类
*
* @author liaokailin
* @version $Id: MyApplicationStartedEventListener.java, v 0.1 2015年9月2日 下午11:06:04 liaokailin Exp $
*/
public class MyApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent> { private Logger logger = LoggerFactory.getLogger(MyApplicationStartedEventListener.class); @Override
public void onApplicationEvent(ApplicationStartedEvent event) {
SpringApplication app = event.getSpringApplication();
app.setShowBanner(false);// 不显示banner信息
logger.info("==MyApplicationStartedEventListener==");
}
}

在该事件中可以获取到SpringApplication对象,可做一些执行前的设置.

Application.java

package com.lkl.springboot;

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

ApplicationEnvironmentPreparedEvent

ApplicationEnvironmentPreparedEvent:spring boot 对应Enviroment已经准备完毕,但此时上下文context还没有创建。

MyApplicationEnvironmentPreparedEventListener.java

package com.lkl.springboot.listener;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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; /**
* spring boot 配置环境事件监听
* @author liaokailin
* @version $Id: MyApplicationEnvironmentPreparedEventListener.java, v 0.1 2015年9月2日 下午11:21:15 liaokailin Exp $
*/
public class MyApplicationEnvironmentPreparedEventListener implements
ApplicationListener<ApplicationEnvironmentPreparedEvent> {
private Logger logger = LoggerFactory.getLogger(MyApplicationEnvironmentPreparedEventListener.class); @Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment envi = event.getEnvironment();
MutablePropertySources mps = envi.getPropertySources();
if (mps != null) {
Iterator<PropertySource<?>> iter = mps.iterator();
while (iter.hasNext()) {
PropertySource<?> ps = iter.next();
logger
.info("ps.getName:{};ps.getSource:{};ps.getClass:{}", ps.getName(), ps.getSource(), ps.getClass());
}
}
} }

在该监听中获取到ConfigurableEnvironment后可以对配置信息做操作,例如:修改默认的配置信息,增加额外的配置信息等等~~~

ApplicationPreparedEvent

ApplicationPreparedEvent:spring boot上下文context创建完成,但此时spring中的bean是没有完全加载完成的。

MyApplicationPreparedEventListener.java

package com.lkl.springboot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext; /**
* 上下文创建完成后执行的事件监听器
*
* @author liaokailin
* @version $Id: MyApplicationPreparedEventListener.java, v 0.1 2015年9月2日 下午11:29:38 liaokailin Exp $
*/
public class MyApplicationPreparedEventListener implements ApplicationListener<ApplicationPreparedEvent> {
private Logger logger = LoggerFactory.getLogger(MyApplicationPreparedEventListener.class); @Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
ConfigurableApplicationContext cac = event.getApplicationContext();
passContextInfo(cac);
} /**
* 传递上下文
* @param cac
*/
private void passContextInfo(ApplicationContext cac) {
//dosomething()
} }

在获取完上下文后,可以将上下文传递出去做一些额外的操作。

在该监听器中是无法获取自定义bean并进行操作的。

ApplicationFailedEvent

ApplicationFailedEvent:spring boot启动异常时执行事件 
MyApplicationFailedEventListener.java

package com.lkl.springboot.listener;

import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener; public class MyApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> { @Override
public void onApplicationEvent(ApplicationFailedEvent event) {
Throwable throwable = event.getException();
handleThrowable(throwable);
} /*处理异常*/
private void handleThrowable(Throwable throwable) {
} }

在异常发生时,最好是添加虚拟机对应的钩子进行资源的回收与释放,能友善的处理异常信息。

在spring boot中已经为大家考虑了这一点,默认情况开启了对应的功能:

public void registerShutdownHook() {
if (this.shutdownHook == null) {
// No shutdown hook registered yet.
this.shutdownHook = new Thread() {
@Override
public void run() {
doClose();
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}

doClose()方法中进行资源的回收与释放。

结束语

spring boot提供的四种监听事件到这里就结束了,针对实际业务可添加自定义的监听器,下一节当中将会对spring boot中的监听源码进行分析,理解为什么是这样的。

spring boot实战(第二篇)事件监听的更多相关文章

  1. spring boot实战(第一篇)第一个案例

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+]   spring boot实战(第一篇)第一个案例 前言 写在前面的话 一直想将spring boot相关内容写成一个系列的 ...

  2. Spring ApplicationContext(八)事件监听机制

    Spring ApplicationContext(八)事件监听机制 本节则重点关注的是 Spring 的事件监听机制,主要是第 8 步:多播器注册:第 10 步:事件注册. public void ...

  3. (转)spring boot实战(第三篇)事件监听源码分析

    原文:http://blog.csdn.net/liaokailin/article/details/48194777 监听源码分析 首先是我们自定义的main方法: package com.lkl. ...

  4. spring boot实战(第十三篇)自动配置原理分析

    前言 spring Boot中引入了自动配置,让开发者利用起来更加的简便.快捷,本篇讲利用RabbitMQ的自动配置为例讲分析下Spring Boot中的自动配置原理. 在上一篇末尾讲述了Spring ...

  5. Spring Cloud实战 | 最终篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案

    一. 前言 在上一篇文章介绍 youlai-mall 项目中,通过整合Spring Cloud Gateway.Spring Security OAuth2.JWT等技术实现了微服务下统一认证授权平台 ...

  6. Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理

    本文完整代码下载点击 一. 前言 相信了解过我或者看过我之前的系列文章应该多少知道点我写这些文章包括创建 有来商城youlai-mall 这个项目的目的,想给那些真的想提升自己或者迷茫的人(包括自己- ...

  7. Spring Boot实践——事件监听

    借鉴:https://blog.csdn.net/Harry_ZH_Wang/article/details/79691994 https://blog.csdn.net/ignorewho/arti ...

  8. 009-Spring Boot 事件监听、监听器配置与方式、spring、Spring boot内置事件

    一.概念 1.事件监听的流程 步骤一.自定义事件,一般是继承ApplicationEvent抽象类 步骤二.定义事件监听器,一般是实现ApplicationListener接口 步骤三.启动时,需要将 ...

  9. spring boot 源码赏析之事件监听

    使用spring Boot已经快1年多了,期间一直想点开springboot源码查看,但由于种种原因一直未能如愿(主要是人类的惰性...),今天就拿springboot 的监听事件祭刀. spring ...

随机推荐

  1. 三、synchronized同步锁

    一.简介 在Java多线程中,我们要实现同步串行最早接触的就是synchronized关键字. 基本语法如下: synchronized(锁) { // 代码块 } sychronized关键字的锁主 ...

  2. 7、包装类、System、Math、Arrays、大数据运算

    基本类型封装 基本数据类型对象包装类概述 *A:基本数据类型对象包装类概述 *a.基本类型包装类的产生 在实际程序使用中,程序界面上用户输入的数据都是以字符串类型进行存储的.而程序开发中,我们需要把字 ...

  3. 为什么要学习 UML?

    UML 的首要价值是沟通和理解.好的图形可以帮助沟通设计思想,尤其是要回避许多细节时,图形也可以帮助你理解软件系统或业务流程.作为团队的成员,尝试弄清楚某些东西时,图形有助于理解和沟通整个团队所理解到 ...

  4. [POI2007]EGZ-Driving Exam

    能到达所有路的充要条件是能到达左右两端的路 用vector反向建边对每条路左右分别求个最长不上升子序列 预处理出每条路向左向右分别需要多建多少路才能到达最左端和最右端 然后跑个\(\Theta(n)\ ...

  5. CSS绝对定位属性

    position - 类型:用于确定定位的类型,共有绝对(absolute).相对(relative)和静态(static)等3种选择. z-index - Z轴:用于控制网页中块元素的叠放顺序,可为 ...

  6. Phoenix 映射 HBase + Maven

    声明 本文基于 Centos6.x + CDH5.x 什么是Phoenix Phoenix的团队用了一句话概括Phoenix:"We put the SQL back in NoSQL&qu ...

  7. 你真的了解Fragment的生命周期吗?

    Android Framwork开发人员中的传奇人物Dianne Hackborn在2010年将Fragment引入了Android,也就是在android3.0之后引入Fragment,他在提交信息 ...

  8. JavaScript运算符优先级引起的bug

    [下面是昨天发给同事的邮件,为防止泄露商业机密,隐去了项目名和变量名] ==================================================== 昨天发现Nx代码中的一 ...

  9. Android设备网络压力测试

    网络测试的几个维度: 网络的性能 带宽:通过TCP测试来量度 时延:用ping命令量度 数据报丢失:用Iperf UDP测试来量度 Jitter(延时变化):用Iperf UDP测试来量度 信号强度( ...

  10. redis在windows上安装+RedisDesktopManager

    redis我就不在这里介绍了,这里直接介绍windows安装redis服务,网上有很多介绍windows版,我这边安装的是一个极简版的. redis官方下载地址:https://redis.io/do ...