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. Java异步转同步

    参考原文: <http://blog.csdn.net/veson__/article/details/53898890>

  2. Java8实战Lambda和Stram API学习

    public  class Trader{        private String name;    private String city; public Trader(String n, St ...

  3. cookie、session、分页

    一.cookie HTTP协议是无状态的. 无状态的意思是每次请求都是独立的,它的执行情况和结果与前面的请求和之后的请求都无直接关系,它不会受前面的请求响应情况直接影响,也不会直接影响后面的请求响应情 ...

  4. js delete 操作符

    delete操作符很陌生,很少会用到,但是既然碰到了,就mark一下: delete 操作符用于删除一个对象的属性: 注意点:只能删除自己的属性,从原型链上继承的属性是无法删除的:

  5. 标签设置为inline-block后,如何消除标签之间的间隔。

    标签设置为inline-block后,如何消除标签之间的间隔. 例如: <div> <ul> <li><a href="#">学习& ...

  6. [HAOI2009]逆序对数列(加强)

    ZJL 的妹子序列 暴力就是 \(\Theta(n\times m)\) 如果 \(n,m \le 10^5\) ? 考虑问题的转换,设 \(a_i\) 表示 \(i\) 小的在它后面的数的个数 \( ...

  7. 分数规划(Bzoj1486: [HNOI2009]最小圈)

    题面 传送门 分数规划 分数规划有什么用? 可以把带分数的最优性求解式化成不带除发的运算 假设求max{\(\frac{a}{b},b>0\)} 二分一个权值\(k\) 令\(\frac{a}{ ...

  8. BZOJ1014: [JSOI2008]火星人prefix(splay 二分 hash)

    题意 题目链接 Sol 一眼splay + 二分hash,不过区间splay怎么写来着呀 试着写了两个小时发现死活不对 看了一下yyb的代码发现自己根本就不会splay.... // luogu-ju ...

  9. RHEL5.X 重启网卡出现./network-functions: line 78: .: ifcfg-eth0: file not found

    错误信息: 红帽RHEL5.5系统,重启网卡报错 [root@localhost network-scripts]# service network restart Shutting down int ...

  10. PHP array_flip() array_merge() array+array的使用总结

    array_flip(array); //传递一个数组参数,对该数组的键.值进行翻转 例如: $a = array( 'a', 'b', 'c' ); print_r(array_flip($a)); ...