spring boot學習(3): SpringApplication 事件監聽

spring application listener

spring 框架中,有多種事件, 這些時間會在不同的運行時刻發佈,來通知監聽者。本文僅僅介紹 SpringApplicationEvent 的事件的監聽。

事件類型

EventType 發佈時間
ApplicationContextInitializedEvent SpringApplication正在啓動, ApplicationContext 已經準備好了,ApplicationContextInitializers 被調用, bean definitions 被加載之前
ApplicationStartingEvent 在一次啓動之前發佈
ApplicationEnvironmentPreparedEvent Environment 準備好之後,會有 context 去使用這一 Environment, 會在 context 創建之前發出
ApplicationPreparedEvent 會在 bean definitions 加載之後,refresh 之前發佈
ApplicationStartedEvent context 更新之後,任何應用或命令行啓動調用之前
ApplicationReadyEvent 任何應用或命令行啓動調用之後發佈,說明應用已經可以被請求了
ApplicationFailedEvent 啓動發生有異常時發步

如何監聽

  1. 監聽器需要使用 org.springframework.context.ApplicationListener 這個接口的實例, 其聲明如下:
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
        /**
     * Handle an application event. * @param event the event to respond to
     */  
    void onApplicationEvent(E event);
}
  1. 需要使用 SpringApplication.addListeners(…​)SpringApplicationBuilder.listeners(…​) 來添加監聽器。也可以在 META-INF/spring.factories 文件中配置:org.springframework.context.ApplicationListener=com.example.project.MyListener

例子:

public class StartingEventListener implements ApplicationListener<ApplicationStartingEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
        System.out.println("called own starting listener");

        System.out.println(applicationStartingEvent.getClass());
    }
}
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args){
        SpringApplication application = new SpringApplication(DemoApplication.class);
        application.addListeners(new StartingEventListener());
        application.run(args);
    }
}

終端運行 jar 包:

$ java -jar build/libs/springlisteners-0.0.1-SNAPSHOT.jar
called own starting listener
class org.springframework.boot.context.event.ApplicationStartingEvent

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章