1. 程式人生 > >SpringBoot入門之事件監聽

SpringBoot入門之事件監聽

int () AI stat boot.s over style 資源 nvi

  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----------
2018-03-03 11:00:58.027  INFO 7644 --- [           main] com.ysl.Application                      : Starting Application on master with PID 7644 (/home/workspace/springboottest/target/classes started by ysl in /home/workspace/springboottest)
2018-03-03 11:00:58.032  INFO 7644 --- [           main] com.ysl.Application                      : No active profile set, falling back to default profiles: default
2018-03-03 11:00:58.182  INFO 7644 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f32bf7: startup date [Sat Mar 03 11:00:58 CST 2018]; 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");
    }
}

運行結果  

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



SpringBoot入門之事件監聽