歡迎您光臨本站 註冊首頁

SpringBoot上下文初始器加載過程詳解

←手機掃碼閱讀     madbeef @ 2020-06-08 , reply:0

利用 Spring 工廠加載機制,實例化 ApplicationContextInitializer 實現類,並排序對象集合。

關鍵方法
 

  privateCollectiongetSpringFactoriesInstances(Classtype,  			Class[] parameterTypes, Object... args) {  		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();  		// Use names and ensure unique to protect against duplicates  		Setnames = new LinkedHashSet<>(  				SpringFactoriesLoader.loadFactoryNames(type, classLoader));  		Listinstances = createSpringFactoriesInstances(type, parameterTypes,  				classLoader, args, names);  		AnnotationAwareOrderComparator.sort(instances);  		return instances;  }

 

技術實現步驟
 

  • 實現類: org.springframework.core.io.support.SpringFactoriesLoader

  • 配置資源: META-INF/spring.factories

  • 排序: AnnotationAwareOrderComparator#sort

自定義初始化器
 

編寫類實現ApplicationContextInitializer接口
 

有兩種指定順序的方法,第一種:類上加註解@Order(Ordered.HIGHEST_PRECEDENCE),第二種則是實現Ordered接口
 

  @Order(Ordered.HIGHEST_PRECEDENCE)  public class HelloWorldApplicationContextInitializerimplements ApplicationContextInitializer{    @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


[madbeef ] SpringBoot上下文初始器加載過程詳解已經有216次圍觀

http://coctec.com/docs/java/show-post-237453.html