springboot源碼解析-管中窺豹系列之Initializer(四)

一、前言

  • Springboot源碼解析是一件大工程,逐行逐句的去研究代碼,會很枯燥,也不容易堅持下去。
  • 我們不追求大而全,而是試着每次去研究一個小知識點,最終聚沙成塔,這就是我們的springboot源碼管中窺豹系列。

 簡介

二、Initializer

  • 上一節我們介紹了Runner,它是在項目加載完成之後執行的
  • 有後就有前,有沒有在項目加載之前執行的呢?

我們今天介紹的ApplicationContextInitializer就是在spring的bean加載之前執行的

public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

	void initialize(C applicationContext);

}
  • 使用很簡單,實現ApplicationContextInitializer接口就可以了
  • 它是先於普通bean加載的,所以不能用@Component的方式
  • 具體怎麼被springboot加載,往下看,我們分析源碼的時候說

三、源碼解析

如果對springboot源碼一點都不了解的,推薦先看第一節:整體架構

1、獲取ApplicationContextInitializer

我們直接先看SpringApplication的構造方法

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    
    ...

    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    
    ...
}    

我們先看setInitializers方法,再看裏面的getSpringFactoriesInstances方法

public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) {
    this.initializers = new ArrayList<>(initializers);
}
  • 很簡單,把查詢的initializers集合賦值到本地變量上
  • 接着看getSpringFactoriesInstances方法,這個initializers集合怎麼查的

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
    return getSpringFactoriesInstances(type, new Class<?>[] {});
}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    ClassLoader classLoader = getClassLoader();
    // 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;
}
  • (1) 獲取ApplicationContextInitializer實現類的名稱集合
  • (2) 加載成實例instances
  • (3) 排序,返回

我們先研究下SpringFactoriesLoader.loadFactoryNames(type, classLoader)這個方法:


public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    String factoryTypeName = factoryType.getName();
    return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null) {
        return result;
    }

    try {
        Enumeration<URL> urls = (classLoader != null ?
                classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        result = new LinkedMultiValueMap<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                String factoryTypeName = ((String) entry.getKey()).trim();
                for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                    result.add(factoryTypeName, factoryImplementationName.trim());
                }
            }
        }
        cache.put(classLoader, result);
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}
  • 注意:factoryType就是我們傳入的參數 ApplicationContextInitializer.class
  • 這裡有個新的map結構:MultiValueMap<String, String>,它和Map<String, List>是一樣的
  • 我們先看一下這裡:classLoader.getResources(FACTORIES_RESOURCE_LOCATION)
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
  • 加載所有的META-INF/spring.factories,按接口名稱放入MultiValueMap<String, String>,並cache
  • 注意,這類文件不止一個,它們分佈在不同的jar包裏面
  • 這麼說你可能不懂,我們看一下這類文件長什麼樣,我們看一個系統自帶的
# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=\
org.springframework.boot.diagnostics.FailureAnalyzers

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.rsocket.context.RSocketPortInfoApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor,\
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor,\
org.springframework.boot.reactor.DebugAgentEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanDefinitionOverrideFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindValidationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.UnboundConfigurationPropertyFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoSuchMethodFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyNameFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyValueFailureAnalyzer

# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter

  • 接口 = 實現類1,實現類2,實現類3
  • 我們假如有了自己的ApplicationContextInitializer實現類,我們在resource下面新建/META-INF/spring.factories文件,按上面的格式寫上就可以被加載了
org.springframework.context.ApplicationContextInitializer=\
org.my.zb.MyApplicationContextInitializer
  • 我們把思維拉回去,講完了怎麼取的實現類名稱集合
  • 回去看 createSpringFactoriesInstances();
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
        ClassLoader classLoader, Object[] args, Set<String> names) {
    List<T> instances = new ArrayList<>(names.size());
    for (String name : names) {
        try {
            Class<?> instanceClass = ClassUtils.forName(name, classLoader);
            Assert.isAssignable(type, instanceClass);
            Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
            T instance = (T) BeanUtils.instantiateClass(constructor, args);
            instances.add(instance);
        }
        catch (Throwable ex) {
            throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
        }
    }
    return instances;
}
  • (1) 獲取Class
  • (2) 獲取構造函數
  • (3) 利用反射新建instance對象
  • (4) 加入集合

至此,我們就得到了:List instances

2、執行ApplicationContextInitializer

我們看SpringApplication的run方法:

public ConfigurableApplicationContext run(String... args) {
    
    ...

    try {
        
        ...

        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        
        ...

    }
    catch (Throwable ex) {
        ...

    }
    
    ...

    return context;
}

進入到prepareContext方法:

private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
        SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    
    ...

    applyInitializers(context);
    
    ...

}

定位到了applyInitializers():

protected void applyInitializers(ConfigurableApplicationContext context) {
    for (ApplicationContextInitializer initializer : getInitializers()) {
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
                ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        initializer.initialize(context);
    }
}
  • 前兩行判斷類型
  • 最後一行回調執行

歡迎關注公眾號:豐極,更多技術學習分享。