天天看點

spring boot實戰(第二篇)事件監聽spring boot實戰(第二篇)事件監聽歡迎關注,您的肯定是對我最大的支援

spring boot實戰(第二篇)事件監聽

前言

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中的監聽源碼進行分析,了解為什麼是這樣的。

轉載請注明

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

歡迎關注,您的肯定是對我最大的支援

spring boot實戰(第二篇)事件監聽spring boot實戰(第二篇)事件監聽歡迎關注,您的肯定是對我最大的支援

繼續閱讀