spring application listener
在 spring 框架中,有多種事件, 這些時間會在不同的運行時刻發(fā)布,來通知監(jiān)聽者。本文僅僅介紹 SpringApplicationEvent 的事件的監(jiān)聽。
事件類型
EventType | 發(fā)布時間 |
---|---|
ApplicationContextInitializedEvent | 在 SpringApplication正在啟動, ApplicationContext 已經準備好了,ApplicationContextInitializers 被調用, bean definitions 被加載之前 |
ApplicationStartingEvent | 在一次啟動之前發(fā)布 |
ApplicationEnvironmentPreparedEvent | 在 Environment 準備好之后,會有 context 去使用這一 Environment, 會在 context 創(chuàng)建之前發(fā)出 |
ApplicationPreparedEvent | 會在 bean definitions 加載之后,refresh 之前發(fā)布 |
ApplicationStartedEvent | context 更新之后,任何應用或命令行啟動調用之前 |
ApplicationReadyEvent | 任何應用或命令行啟動調用之后發(fā)布,說明應用已經可以被請求了 |
ApplicationFailedEvent | 啟動發(fā)生有異常時發(fā)步 |
如何監(jiān)聽
監(jiān)聽器需要使用 org.springframework.context.ApplicationListener 這個接口的實例, 其聲明如下:
@FunctionalInterfacepublic interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * Handle an application event. * @param event the event to respond to */ void onApplicationEvent(E event);}
需要使用 SpringApplication.addListeners(…?) 或 SpringApplicationBuilder.listeners(…?) 來添加監(jiān)聽器。也可以在 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()); }}
@SpringBootApplicationpublic 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.jarcalled own starting listenerclass org.springframework.boot.context.event.ApplicationStartingEvent . ____ _ __ _ _ /// / ___'_ __ _ _(_)_ __ __ _ / / / /( ( )/___ | '_ | '_| | '_ // _` | / / / / /// ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_/__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.3.RELEASE)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選