SpringBoot上下文初始器加載過程詳解
利用 Spring 工廠加載機(jī)制,實(shí)例化 ApplicationContextInitializer 實(shí)現(xiàn)類,并排序?qū)ο蠹稀?/p>
關(guān)鍵方法
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
技術(shù)實(shí)現(xiàn)步驟
- 實(shí)現(xiàn)類: org.springframework.core.io.support.SpringFactoriesLoader
- 配置資源: META-INF/spring.factories
- 排序: AnnotationAwareOrderComparator#sort
自定義初始化器
編寫類實(shí)現(xiàn)ApplicationContextInitializer接口
有兩種指定順序的方法,第一種:類上加注解@Order(Ordered.HIGHEST_PRECEDENCE),第二種則是實(shí)現(xiàn)Ordered接口
@Order(Ordered.HIGHEST_PRECEDENCE)
public class HelloWorldApplicationContextInitializer<C extends ConfigurableApplicationContext>
implements ApplicationContextInitializer<C> {
@Override
public void initialize(C applicationContext) {
System.out.println("ConfigurableApplicationContext.id = "+ applicationContext.getId());
}
}
public class AfterHelloWorldApplicationContextInitializer implements ApplicationContextInitializer, Ordered {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("After application.id = " + applicationContext.getId());
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
在spring.properties中配置
# ApplicationContextInitializer
org.springframework.context.ApplicationContextInitializer=\
com.imooc.diveinspringboot.context.AfterHelloWorldApplicationContextInitializer,\
com.imooc.diveinspringboot.context.HelloWorldApplicationContextInitializer
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java緩存Map設(shè)置過期時(shí)間實(shí)現(xiàn)解析
這篇文章主要介紹了Java緩存Map設(shè)置過期時(shí)間實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法
這篇文章主要介紹了在Android的應(yīng)用中實(shí)現(xiàn)網(wǎng)絡(luò)圖片異步加載的方法,一定程度上有助于提高安卓程序的使用體驗(yàn),需要的朋友可以參考下2015-07-07
java的SimpleDateFormat線程不安全的幾種解決方案
但我們知道SimpleDateFormat是線程不安全的,處理時(shí)要特別小心,要加鎖或者不能定義為static,要在方法內(nèi)new出對(duì)象,再進(jìn)行格式化,本文就介紹了幾種方法,感興趣的可以了解一下2021-08-08
Spring連接Mysql數(shù)據(jù)庫的實(shí)現(xiàn)步驟
本文主要介紹了Spring連接Mysql數(shù)據(jù)庫的實(shí)現(xiàn)步驟,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03

