Spring Boot中的initializers的作用分析

Posted 源码王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot中的initializers的作用分析相关的知识,希望对你有一定的参考价值。

在SpringApplication的实例属性中有一个初始器的属性:List<ApplicationContextInitializer<?>> initializers ,这些初始化器(initializers)是Spring Boot通过读取每个jar包下的/META-INF/spring.factories文件中的配置获取的。每一个initailizer都是一个实现了ApplicationContextInitializer接口的实例。ApplicationContextInitializer是Spring IOC容器中提供的一个接口:

package org.springframework.context;


public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

    /**
     * Initialize the given application context.
     * @param applicationContext the application to configure
     */
    void initialize(C applicationContext);

}
ApplicationContextInitializer是一个回调接口,它会在ConfigurableApplicationContext的refresh()方法调用之前被调用,做一些容器的初始化工作。

SpringBoot默认情况下提供了6个initializer,分别由2个jar提供:

 spring-boot-1.5.2.RELEASE.jar

  •   org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,
  •   org.springframework.boot.context.ContextIdApplicationContextInitializer,
  •   org.springframework.boot.context.config.DelegatingApplicationContextInitializer,
  •   org.springframework.boot.context.embedded.ServerPortInfoApplicationContextInitializer

  

   spring-boot-autoconfigure-1.5.2.RELEASE.jar

  •   org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,
  •   org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

 

 Spring Boot对initializer的获取过程如下:

initialize(Object[] sources)
  -->getSpringFactoriesInstances(type, new Class<?>[] {})
      -->SpringFactoriesLoader.loadFactoryNames(type, classLoader))
      -->createSpringFactoriesInstances(type, parameterTypes,classLoader, args, names)
        -->Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes)
        -->T instance = (T) BeanUtils.instantiateClass(constructor, args)
      -->AnnotationAwareOrderComparator.sort(instances)

      -->setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class ))

   -->this.initializers = new ArrayList<ApplicationContextInitializer<?>>();

   -->this.initializers.addAll(initializers);    //存入List<ApplicationContextInitializer<?>> initializers

 

以上是关于Spring Boot中的initializers的作用分析的主要内容,如果未能解决你的问题,请参考以下文章

入门SpringBoot-Spring Initializer快速创建Spring Boot项目

spring boot:JPA org.hibernate.LazyInitializationException: could not initialize proxy [XXX#1] - n(代码

spring boot 集成axis1.4 java.lang.NoClassDefFoundError: Could not initialize class org.apache.axis.cl

Spring Boot启动流程

spring Boot启动报错Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.s

Spring.datasource.initialize=false 不工作