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中名词的解释

    在上一篇中说到了Java的四大特性,里面出现了很多名次,包括以后学习Java中也会出现很多常用到的名次,对初学者来说可能不知道是什么意思,或者是对这些刺耳的理解不是特别透彻,这里我就我自己的理解来解释 ...

  2. JMX 远程监控 Linux tomcat 功能实现

    作者远程服务器操作系统 CentOS 7.0, tomcat 版本 7.0 1. Linux tomcat 配置 1.1 catalina_opt 配置 可以在 catalina.sh 文件中添加如下 ...

  3. hdu 3999 二叉查找树

    The order of a Tree Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Othe ...

  4. vue-router初涉

    概念: vue-router: vue官方路由插件. 路由: 指单页面应用的路径管理系统.在vue中都是单页应用,相当于只有一个index.html页面,所以无法使用<a>标签,我们使用路 ...

  5. Android 显示html标签或者带图片

    Android中显示html文件要用Html.fromHtml(...)处理过的返回值,返回值可以成为setText()的参数. 只显示带文本的html可以用下面的方法处理html文件. public ...

  6. Java期中项目杂七杂八

    这是一篇草稿,嗯,等结项以后大概可能会整理其中的一部分吧…… 杂项 1. 用Idea创建Maven项目:直接选就行:至于商定好的Eclipse要怎么做再说…… 2. 联网依赖:选择我们最熟的okhtt ...

  7. [学习] nofollow

    [来源:百度百科 http://baike.baidu.com/view/1584081.htm] 简介 nofollow[1]是一个HTML标签的属性值.它的出现为网站管理员提供了一种方式,即告诉搜 ...

  8. 基于PMBOK的项目管理知识体系

  9. CentOS6.5 SSH无法连接

    1.确认连接交机机端口的正常,如查更换多几个端口试 2.确认网络不存在问题. 3.把selinux iptables服务全部关闭 4.查看本机是否侦听22端口和是否开启ssh服务 命令:netstat ...

  10. 已经不再使用的表为什么数据页还在SQLServer的内存缓存中

    1. 问题发现 在学习内存调优时,使用如下代码,查询目前内存缓冲区中生产数据库的每个对象缓存页计数 SELECT count(*)AS cached_pages_count ,name ,index_ ...