SpringBoot入門之事件監聽

  spring boot在啓動過程當中增長事件監聽機制,爲用戶功能拓展提供極大的便利,sptingboot支持的事件類型有如下五種:java

  • ApplicationStartingEvent
  • ApplicationFailedEvent
  • ApplicationPreparedEvent
  • ApplicationReadyEvent
  • ApplicationEnvironmentPreparedEvent

實現監聽步驟spring

  1.監聽類實現ApplicationListener接口springboot

  2.將監聽類添加到SpringApplication實例中app

ApplicationStartingEvent

  ApplicationStartingEvent:springboot啓動開始的時候執行的事件,在該事件中能夠獲取到SpringApplication對象,可作一些執行前的設置。ide

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);
    }
}

執行結果以下:spa

--------- 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後能夠對配置信息作操做,例如:修改默認的配置信息,增長額外的配置信息等等。code

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並進行操做的。blog

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)
相關文章
相關標籤/搜索