SpringBoot啟動程式碼和自動裝配原始碼分析

bei_er 發表於 2022-07-04
Spring

​ 隨著網際網路的快速發展,各種元件層出不窮,需要框架整合的元件越來越多。每一種元件與Spring容器整合需要實現相關程式碼。SpringMVC框架配置由於太過於繁瑣和依賴XML檔案;為了方便快速整合第三方元件和減少對配置檔案的依賴,SpringBoot應運而生,其中採用了約定大於配置的理論讓開發者不需要過多配置即可進行開發。SpringBoot底層使用的Spring ,預設整合了N多元件的自動裝配。使用SpringBoot很簡單,在主類中新增一個@SpringBootApplication,以及呼叫SpringApplication.run()並傳入主類。程式碼如下

@SpringBootApplication
public class StartApp {
    public static void main(String[] args) {
        SpringApplication.run(StartApp.class);
    }
}

由上面的原始碼可知,SpringApplication.run()是SpringBoot的程式入口。本文會從SpringApplication.run()和@SpringBootApplication註解兩方面來分析。

一、SpringBoot啟動程式碼主線分析

​ SpringApplication.run(StartApp.class)的中關鍵程式碼,先建立一個SpringApplication類,再執行run方法。程式碼如下,

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
   return new SpringApplication(primarySources).run(args);
}
  1. SpringApplication的構造方法程式碼如下
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    // 設定資源載入器
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    // 設定應用主配置類
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    // 獲取web伺服器型別
    this.webApplicationType = WebApplicationType.deduceFromClasspath();
    // 從spring.factories 檔案中獲取 ApplicationContextInitializer 的實現類
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    // 從spring.factories 檔案中獲取 ApplicationListener 監聽器的實現類
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    // 設定main啟動類
    this.mainApplicationClass = deduceMainApplicationClass();
}

構造方法中主要邏輯:

​ 1.設定應用主配置類,後面的run方法中會用它封裝成 BeanDefinitionHolder 並載入到 context 的 registry 中。

​ 2.獲取web伺服器型別,後面的run方法中會用它來建立具體的web服務型別。

​ 3.從spring.factories 檔案中獲取 ApplicationContextInitializer 的實現類,並設定給SpringApplication例項

​ 4.從spring.factories 檔案中獲取 ApplicationListener 監聽器的實現類,並設定給SpringApplication例項

​ 5.設定main啟動類

其中getSpringFactoriesInstances方法主要邏輯是:從META-INF/spring.factories檔案中根據介面獲取具體實現類字串,並把字串成例項化為物件。程式碼如下,

// 獲取類載入器
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
// 根據type 從META-INF/spring.factories獲取 具體的實現類字串列表
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 例項化具體的實現類
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
// 排序
AnnotationAwareOrderComparator.sort(instances);
return instances;

在META-INF/spring.factories檔案中ApplicationContextInitializer.class 對應的實現類字串為,

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

在META-INF/spring.factories檔案中ApplicationListener.class 對應的實現類字串為,

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
  1. run方法的程式碼如下,
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
// 設定了一個名為 java.awt.headless 的系統屬性
// 其實是想設計應用程式,即使沒有檢測到顯示器,也允許其啟動
// 對於伺服器來說,是不需要顯示器的 ,所以要這樣設定
configureHeadlessProperty();
// 獲取 SpringApplicationRunListener 載入的是 EventPublishingRunListener
// 獲取啟動時的監聽器
SpringApplicationRunListeners listeners = getRunListeners(args);
// 觸發啟動事件
listeners.starting();
try {
    // 構造一個應用程式的引數持有類
    ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    // 建立並配置環境
    ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
    // 配置需要忽略的BeanInfo資訊
    configureIgnoreBeanInfo(environment);
    Banner printedBanner = printBanner(environment);
    // 建立上下文物件
    context = createApplicationContext();
    // 載入配置的啟動異常處理器
    exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                                     new Class[] { ConfigurableApplicationContext.class }, context);
    // 重新整理前操作
    prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    // 重新整理應用上下文 完成 Spring 容器的初始化
    refreshContext(context);
    // 重新整理後操作
    afterRefresh(context, applicationArguments);
    stopWatch.stop();
    if (this.logStartupInfo) {
        new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
    }
    // 啟動完成事件
    listeners.started(context);
    // 執行 ApplicationRunner 和 CommandLineRunner 實現類
    callRunners(context, applicationArguments);
}
catch (Throwable ex) {
    // 事件廣播啟動出錯了
    handleRunFailure(context, ex, exceptionReporters, listeners);
    throw new IllegalStateException(ex);
}

try {
    // 執行事件
    listeners.running(context);
}
catch (Throwable ex) {
    handleRunFailure(context, ex, exceptionReporters, null);
    throw new IllegalStateException(ex);
}
return context;

run方法中主要邏輯:

​ 1. 從spring.factories 檔案中獲取 SpringApplicationRunListener 的實現類(監聽事件釋出器),並在context生命週期中執行相關的事件 ,比如觸發啟動事件、啟動完成事件等。

​ 2.建立Web應用上下文物件,根據webApplicationType來建立具體的web服務型別。

​ 3.重新整理前操作,把主配置類資源封裝成 BeanDefinitionHolder 載入到 context 的 registry 中。

​ 4.重新整理應用上下文 完成 Spring 容器的初始化。

​ 5.執行 實現了 ApplicationRunner 和 CommandLineRunner 介面的類。

二、SpringBoot自動裝配原理分析

1.自動裝配的前置知識@Import

​ @SpringBootApplication註解其中主要是利用@Import 註解,@Import原始碼如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

    /**
	 * {@link Configuration @Configuration}, {@link ImportSelector},
	 * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
	 */
    Class<?>[] value();

}

@Import在註解一般和@Configuration一起用,Spring容器初始化的過程中會進行解析@Configuration註解類(原始碼在org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions中),其過程會解析註解類的@Import註解的後設資料,並根據類是否實現相關介面進行處理。原始碼位置:org.springframework.context.annotation.ConfigurationClassParser#processImports;關鍵程式碼如下,

try {
    for (SourceClass candidate : importCandidates) {
        if (candidate.isAssignable(ImportSelector.class)) {
            // Candidate class is an ImportSelector -> delegate to it to determine imports
            Class<?> candidateClass = candidate.loadClass();
            ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
                                                                           this.environment, this.resourceLoader, this.registry);
            Predicate<String> selectorFilter = selector.getExclusionFilter();
            if (selectorFilter != null) {
                exclusionFilter = exclusionFilter.or(selectorFilter);
            }
            if (selector instanceof DeferredImportSelector) {
                this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
            }
            else {
                String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
                Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
                processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
            }
        }
        else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
            // Candidate class is an ImportBeanDefinitionRegistrar ->
            // delegate to it to register additional bean definitions
            Class<?> candidateClass = candidate.loadClass();
            ImportBeanDefinitionRegistrar registrar =
                ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
                                                     this.environment, this.resourceLoader, this.registry);
            configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
        }
        else {
            // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
            // process it as an @Configuration class
            this.importStack.registerImport(
                currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
            processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
        }
    }
}

從上面程式碼可知@Import的value類使用有三種場景:

​ 1.實現了 ImportSelector.class介面的場景;直接呼叫例項selector 的selectImports方法返回要例項化的Bean物件的全類名列表,並根據全類名字串列表建立例項物件,然後遞迴呼叫當前的processImports 方法,最終會新增到configurationClasses的集合中,configurationClasses集合中的物件會被註冊到BeanDefinitionRegistry型別的 registry 物件中。實現介面ImportSelector這種情況下又擴充套件了 DeferredImportSelector 介面的情況,該介面用來實現BeanDefinition的延遲注入功能更。DeferredImportSelector介面擴充套件了ImportSelector介面,並且其中有個內部介面 Group,如果某個@Import註解的value類實現了DeferredImportSelector介面並且也實現了該介面的內部類Group介面,則表面此實現類需要延遲處理。如果是需要延遲處理,則會把ImportSelector 例項selector 組裝成 DeferredImportSelectorHolder 物件新增到 deferredImportSelectors集合中,處理邏輯原始碼位置: org.springframework.context.annotation.ConfigurationClassParser.DeferredImportSelectorHandler#handle;關鍵程式碼如下,

public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
    DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(configClass, importSelector);
    if (this.deferredImportSelectors == null) {
        DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
        handler.register(holder);
        handler.processGroupImports();
    }
    else {
        this.deferredImportSelectors.add(holder);
    }
}

DeferredImportSelector介面的實現邏輯會在org.springframework.context.annotation.ConfigurationClassParser#parse方法中呼叫,具體程式碼在this.deferredImportSelectorHandler.process()中,關鍵程式碼如下,

public void process() {
    List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
    this.deferredImportSelectors = null;
    try {
        if (deferredImports != null) {
            DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
            deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
            deferredImports.forEach(handler::register);
            // 具體的執行邏輯
            handler.processGroupImports();
        }
    }
    finally {
        this.deferredImportSelectors = new ArrayList<>();
    }
}

在processGroupImports()方法中,先通過grouping.getImports()拿到需要自動裝配的Group.Entry(封裝了全類名)物件集合,然後通過processImports()方法根據Entry類名字串進行建立SourceClass類(該類可以通過asConfigClass()方法轉成ConfigurationClass物件),最終新增到configurationClasses集合中。程式碼如下,

public void processGroupImports() {
    for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
        Predicate<String> exclusionFilter = grouping.getCandidateFilter();
        grouping.getImports().forEach(entry -> {
            ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata());
            try {
                processImports(configurationClass, asSourceClass(configurationClass, exclusionFilter),
                               Collections.singleton(asSourceClass(entry.getImportClassName(), exclusionFilter)),
                               exclusionFilter, false);
            }
            catch (BeanDefinitionStoreException ex) {
                throw ex;
            }
            catch (Throwable ex) {
                throw new BeanDefinitionStoreException(
                    "Failed to process import candidates for configuration class [" +
                    configurationClass.getMetadata().getClassName() + "]", ex);
            }
        });
    }
}

grouping.getImports()方法中主要執行具體的實現類的process方法和selectImports()方法(如果是AutoConfigurationImportSelector類,則呼叫org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process和org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#selectImports,兩個方法的具體類容請看2.2.2章節的說明),selectImports返回需要自動裝配的Group.Entry物件集合,Entry物件中儲存了全類名。程式碼如下:

public Iterable<Group.Entry> getImports() {
    for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
        this.group.process(deferredImport.getConfigurationClass().getMetadata(),
                           deferredImport.getImportSelector());
    }
    return this.group.selectImports();
}

ImportSelector介面程式碼程式碼如下:

public interface ImportSelector {
	String[] selectImports(AnnotationMetadata importingClassMetadata);
	@Nullable
	default Predicate<String> getExclusionFilter() {
		return null;
	}
}

DeferredImportSelector介面的程式碼如下:

public interface DeferredImportSelector extends ImportSelector {

    @Nullable
    default Class<? extends Group> getImportGroup() {
        return null;
    }
    interface Group {
        void process(AnnotationMetadata metadata, DeferredImportSelector selector);
        Iterable<Entry> selectImports();
        class Entry {
			// 省略
        }
    }
}

​ 2.實現了 ImportBeanDefinitionRegistrar.class介面的場景;會先建立ImportBeanDefinitionRegistrar 例項類 registrar,再把 registrar 新增到 configClass 的 importBeanDefinitionRegistrars中,介面的registerBeanDefinitions方法的呼叫是在 org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions方法裡的this.reader.loadBeanDefinitions(configClasses)程式碼中。具體執行語句loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());關鍵程式碼如下,

private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
    registrars.forEach((registrar, metadata) ->
                       registrar.registerBeanDefinitions(metadata, this.registry, this.importBeanNameGenerator));
}

ImportBeanDefinitionRegistrar介面程式碼如下:

public interface ImportBeanDefinitionRegistrar {

    default void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry,
                                         BeanNameGenerator importBeanNameGenerator) {
        registerBeanDefinitions(importingClassMetadata, registry);
    }

    default void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    }
}

​ 3.沒有實現以上兩介面的普通類,會直接呼叫org.springframework.context.annotation.ConfigurationClassParser#processImports裡面的processConfigurationClass方法,把當前configClass新增至 configurationClasses 集合中。configurationClasses集合中的物件最終會被註冊到BeanDefinitionRegistry型別的 registry 物件中。

[email protected]註解分析

​ @SpringApplication註解主要包括了@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。程式碼如下,

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

[email protected]

​ 配置註解,包含了@Configuration註解,表明是配置類。

[email protected]

​ 自動裝配註解,主要邏輯是:根據 EnableAutoConfiguration 型別從META-INF/spring.factories 檔案載入需要自動裝配的類,並注入到Spring容器中。它包括了@AutoConfigurationPackage註解和一個@Import(AutoConfigurationImportSelector.class)註解。程式碼如下,

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
[email protected]

​ 註冊名為 org.springframework.boot.autoconfigure.AutoConfigurationPackages ,BeanClass為BasePackages.class 的GenericBeanDefinition 到 BeanDefinitionRegistry 中,通過@Import 註解實現注入功能,程式碼如下,

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
}

AutoConfigurationPackages.Registrar.class實現了ImportBeanDefinitionRegistrar介面 ,所以在Spring容器初始化的過程中會呼叫它的registerBeanDefinitions方法把PackageImport類注入到Spring容器中去。程式碼如下,

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        register(registry, new PackageImport(metadata).getPackageName());
    }
    @Override
    public Set<Object> determineImports(AnnotationMetadata metadata) {
        return Collections.singleton(new PackageImport(metadata));
    }
}
[email protected](AutoConfigurationImportSelector.class)

​ 自動裝配關鍵邏輯,先從META-INF/spring.factories 檔案載入型別值為 EnableAutoConfiguration的字串集合,再通過過濾,生成需要自動裝配的類,最後注入到Spring容器中。AutoConfigurationImportSelector實現了DeferredImportSelector介面並且內部也實現了DeferredImportSelector.Group介面,所以在Spring容器初始化的過程中會呼叫

org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process方法和#selectImports方法,

  1. process()用來生成需要自動裝配的型別,方法的程式碼如下,
Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
             () -> String.format("Only %s implementations are supported, got %s",
                                 AutoConfigurationImportSelector.class.getSimpleName(),
                                 deferredImportSelector.getClass().getName()));
// 1. getAutoConfigurationMetadata()
// 從META-INF/spring-autoconfigure-metadata.properties檔案中獲取自動裝配的後設資料,
// 裡面儲存了載入類是否自動裝配的條件 ,
// org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration.ConditionalOnBean
// =javax.jms.ConnectionFactory
// 2. getAutoConfigurationEntry()
// 從 META-INF/spring.factories 檔案中獲取key為 EnableAutoConfiguration 的配置類字串類表 並封裝成 自動裝配類物件
AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
    .getAutoConfigurationEntry(getAutoConfigurationMetadata(), annotationMetadata);
this.autoConfigurationEntries.add(autoConfigurationEntry);
// 迴圈遍歷 自動裝配類物件 的自動裝配類字串 ,新增到 this.entries
for (String importClassName : autoConfigurationEntry.getConfigurations()) {
    this.entries.putIfAbsent(importClassName, annotationMetadata);
}

getAutoConfigurationMetadata() 方法主要邏輯是:從META-INF/spring-autoconfigure-metadata.properties檔案中獲取自動裝配的後設資料,裡面儲存了自動載入類是否符合自動裝配的前置條件,比較熟悉的有ConditionalOnClass和ConditionalOnBean,檔案相關內容如下:

org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration=
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration.AutoConfigureAfter=org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration.ConditionalOnClass=com.datastax.driver.core.Cluster,reactor.core.publisher.Flux,org.springframework.data.cassandra.core.ReactiveCassandraTemplate
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration.ConditionalOnClass=org.apache.solr.client.solrj.SolrClient,org.springframework.data.solr.repository.SolrRepository
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration.ConditionalOnWebApplication=SERVLET
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration=
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration.AutoConfigureBefore=org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.jms.artemis.ArtemisXAConnectionFactoryConfiguration=
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration.ConditionalOnWebApplication=REACTIVE
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration.ConditionalOnWebApplication=REACTIVE
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration=
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration.ConditionalOnWebApplication=SERVLET
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration.ConditionalOnWebApplication=SERVLET
//省略

getAutoConfigurationEntry()方法 主要邏輯是:從spring.factories 檔案中獲取key為 EnableAutoConfiguration 的配置類字串列表並封裝成自動裝配類AutoConfigurationEntry物件,程式碼如下,

protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
                                                           AnnotationMetadata annotationMetadata) {
    if (!isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    }
    // 獲取註解後設資料的屬性
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
    // 從spring.factories 檔案中獲取key為 EnableAutoConfiguration 的配置類字串列表
    List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
    // 去掉重複的 自動裝配類字串
    configurations = removeDuplicates(configurations);
    // 根據註解後設資料獲取 需要排除的類名
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    // 檢查排除的類名
    checkExcludedClasses(configurations, exclusions);
    // 根據排除的類名進行排除
    configurations.removeAll(exclusions);
    // 從spring.factories 檔案中獲取key為 AutoConfigurationImportFilter 的配置物件進行過濾
    // 過濾規則從 getAutoConfigurationMetadata() 返回類的資料中獲取
    configurations = filter(configurations, autoConfigurationMetadata);
    // 執行匯入配置類的監聽事件
    fireAutoConfigurationImportEvents(configurations, exclusions);
    // 返回 AutoConfigurationEntry 物件
    return new AutoConfigurationEntry(configurations, exclusions);
}

getCandidateConfigurations()方法從spring.factories 檔案中獲取型別為 EnableAutoConfiguration 的配置類字串列表,程式碼如下,

// getSpringFactoriesLoaderFactoryClass()方法返回 EnableAutoConfiguration
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;

在META-INF/spring.factories檔案中EnableAutoConfiguration .class 對應的實現類字串為

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
// 省略
  1. selectImports()方法返回排序後的 Entry(需要自動裝配的包裝實體類) 物件集合,程式碼如下,
public Iterable<Entry> selectImports() {
    if (this.autoConfigurationEntries.isEmpty()) {
        return Collections.emptyList();
    }
    Set<String> allExclusions = this.autoConfigurationEntries.stream()
        .map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
    Set<String> processedConfigurations = this.autoConfigurationEntries.stream()
        .map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream)
        .collect(Collectors.toCollection(LinkedHashSet::new));
    processedConfigurations.removeAll(allExclusions);
    // 返回排序後的 Entry 集合
    return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream()
        .map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
        .collect(Collectors.toList());
}

注意:@EnableAutoConfiguration 註解的分析過程需要結合@Import註解的過程來看。

[email protected]

​ 元件掃描註解,用來配置自動掃描包路徑。如果沒有配置路徑,則掃描主配置類名稱空間下的所有包和類。