springBoot的事件機制GenericApplicationListener用法解析
什么是ApplicationContext?
它是Spring的核心,Context我們通常解釋為上下文環(huán)境,但是理解成容器會更好些。 ApplicationContext則是應(yīng)用的容器。
Spring把Bean(object)放在容器中,需要用就通過get方法取出來。
ApplicationEvent
- 是個抽象類,里面只有一個構(gòu)造函數(shù)和一個長整型的timestamp。
- springboot的event的類型:
- ApplicationStartingEvent
- ApplicationEnvironmentPreparedEvent
- ApplicationContextInitializedEvent
- ApplicationPreparedEvent
- ContextRefreshedEvent
- ServletWebServerInitializedEvent
- ApplicationStartedEvent
- ApplicationReadyEvent
ApplicationListener
是一個接口,里面只有一個onApplicationEvent方法。所以自己的類在實現(xiàn)該接口的時候,要實現(xiàn)該方法。
ApplicationListener的封裝類
- GenericApplicationListener
- GenericApplicationListenerAdapter
- SmartApplicationListener
關(guān)系
如果在上下文中部署一個實現(xiàn)了ApplicationListener接口的bean,那么每當在一個ApplicationEvent發(fā)布到 ApplicationContext時,這個bean得到通知。其實這就是標準的Oberver設(shè)計模式。
注意
要配置META-INF/spring.factories文件,并在文件中實現(xiàn)
使用
// 第一種方式 public class AiInfluxdbApplicationListener implements GenericApplicationListener { @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } @Override public boolean supportsEventType(ResolvableType eventType) { return ApplicationReadyEvent.class.isAssignableFrom(eventType.getRawClass()); } @Override public void onApplicationEvent(ApplicationEvent event) { System.out.print("here is ApplicationReadyEvent"); } } //第二種方式 public class ConfigApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered { @Override public int getOrder() { return HIGHEST_PRECEDENCE; } @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { } } //META-INF/spring.factories文件定義 org.springframework.context.ApplicationListener=\ com.demotest.core.ApplicationStartListener
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合flyway實現(xiàn)自動創(chuàng)建表的方法
這篇文章主要介紹了SpringBoot整合flyway實現(xiàn)自動創(chuàng)建表的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Java連接合并2個數(shù)組(Array)的5種方法例子
最近在寫代碼時遇到了需要合并兩個數(shù)組的需求,突然發(fā)現(xiàn)以前沒用過,于是研究了一下合并數(shù)組的方式,這篇文章主要給大家介紹了關(guān)于Java連接合并2個數(shù)組(Array)的5種方法,需要的朋友可以參考下2023-12-12