日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網(wǎng)為廣大站長提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請做好本站友鏈:【 網(wǎng)站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

隨著互聯(lián)網(wǎng)的快速發(fā)展,各種組件層出不窮,需要框架集成的組件越來越多。每一種組件與Spring容器整合需要實(shí)現(xiàn)相關(guān)代碼。SpringMVC框架配置由于太過于繁瑣和依賴XML文件;為了方便快速集成第三方組件和減少對配置文件的依賴,SpringBoot應(yīng)運(yùn)而生,其中采用了約定大于配置的原則讓開發(fā)者不需要過多配置即可進(jìn)行開發(fā)。SpringBoot底層使用的Spring ,默認(rèn)集成了N多組件的自動裝配。使用SpringBoot很簡單,在主類中添加一個@SpringBootApplication,以及調(diào)用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)的中關(guān)鍵代碼,先創(chuàng)建一個SpringApplication類,再執(zhí)行run方法。代碼如下,

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
   return new SpringApplication(primarySources).run(args);
}
  1. SpringApplication的構(gòu)造方法代碼如下
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    // 設(shè)置資源加載器
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    // 設(shè)置應(yīng)用主配置類
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    // 獲取web服務(wù)器類型
    this.webApplicationType = WebApplicationType.deduceFromClasspath();
    // 從spring.factories 文件中獲取 ApplicationContextInitializer 的實(shí)現(xiàn)類
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    // 從spring.factories 文件中獲取 ApplicationListener 監(jiān)聽器的實(shí)現(xiàn)類
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    // 設(shè)置main啟動類
    this.mainApplicationClass = deduceMainApplicationClass();
}

構(gòu)造方法中的主要邏輯:

? 1.設(shè)置應(yīng)用主配置類,后面的run方法中會用它封裝成 BeanDefinitionHolder 并加載到 context 的 registry 中。

? 2.獲取web服務(wù)器類型,后面的run方法中會用它來創(chuàng)建具體的web服務(wù)類型。

? 3.從spring.factories 文件中獲取
ApplicationContextInitializer 的實(shí)現(xiàn)類,并設(shè)置給SpringApplication實(shí)例

? 4.從spring.factories 文件中獲取 ApplicationListener 監(jiān)聽器的實(shí)現(xiàn)類,并設(shè)置給SpringApplication實(shí)例

? 5.設(shè)置main啟動類

其中
getSpringFactoriesInstances方法主要邏輯是:從META-INF/spring.factories文件中根據(jù)接口獲取具體實(shí)現(xiàn)類字符串,并把字符串成實(shí)例化為對象。代碼如下,

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

在META-INF/spring.factories文件中
ApplicationContextInitializer.class 對應(yīng)的實(shí)現(xiàn)類字符串為,

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 對應(yīng)的實(shí)現(xiàn)類字符串為,

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<>();
// 設(shè)置了一個名為 JAVA.awt.headless 的系統(tǒng)屬性
// 其實(shí)是想設(shè)計(jì)應(yīng)用程序,即使沒有檢測到顯示器,也允許其啟動
// 對于服務(wù)器來說,是不需要顯示器的 ,所以要這樣設(shè)置
configureHeadlessProperty();
// 獲取 SpringApplicationRunListener 加載的是 EventPublishingRunListener
// 獲取啟動時的監(jiān)聽器
SpringApplicationRunListeners listeners = getRunListeners(args);
// 觸發(fā)啟動事件
listeners.starting();
try {
    // 構(gòu)造一個應(yīng)用程序的參數(shù)持有類
    ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    // 創(chuàng)建并配置環(huán)境
    ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
    // 配置需要忽略的BeanInfo信息
    configureIgnoreBeanInfo(environment);
    Banner printedBanner = printBanner(environment);
    // 創(chuàng)建上下文對象
    context = createApplicationContext();
    // 加載配置的啟動異常處理器
    exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                                     new Class[] { ConfigurableApplicationContext.class }, context);
    // 刷新前操作
    prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    // 刷新應(yīng)用上下文 完成 Spring 容器的初始化
    refreshContext(context);
    // 刷新后操作
    afterRefresh(context, applicationArguments);
    stopWatch.stop();
    if (this.logStartupInfo) {
        new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
    }
    // 啟動完成事件
    listeners.started(context);
    // 執(zhí)行 ApplicationRunner 和 CommandLineRunner 實(shí)現(xiàn)類
    callRunners(context, applicationArguments);
}
catch (Throwable ex) {
    // 事件廣播啟動出錯了
    handleRunFailure(context, ex, exceptionReporters, listeners);
    throw new IllegalStateException(ex);
}

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

run方法中主要邏輯:

? 1. 從spring.factories 文件中獲取
SpringApplicationRunListener 的實(shí)現(xiàn)類(監(jiān)聽事件發(fā)布器),并在context生命周期中執(zhí)行相關(guān)的事件 ,比如觸發(fā)啟動事件、啟動完成事件等。

? 2.創(chuàng)建Web應(yīng)用上下文對象,根據(jù)webApplicationType來創(chuàng)建具體的web服務(wù)類型。

? 3.刷新前操作,把主配置類資源封裝成 BeanDefinitionHolder 加載到 context 的 registry 中。

? 4.刷新應(yīng)用上下文 完成 Spring 容器的初始化。

? 5.執(zhí)行 實(shí)現(xiàn)了 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容器初始化的過程中會進(jìn)行解析@Configuration注解類(源碼在
org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions中),其過程會解析注解類的@Import注解的元數(shù)據(jù),并根據(jù)類是否實(shí)現(xiàn)相關(guān)接口進(jìn)行處理。源碼位置:org.springframework.context.annotation.ConfigurationClassParser#processImports;關(guān)鍵代碼如下,

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.實(shí)現(xiàn)了 ImportSelector.class接口的場景;直接調(diào)用實(shí)例selector 的selectImports方法返回要實(shí)例化的Bean對象的全類名列表,并根據(jù)全類名字符串列表創(chuàng)建實(shí)例對象,然后遞歸調(diào)用當(dāng)前的processImports 方法,最終會添加到configurationClasses的集合中,configurationClasses集合中的對象會被注冊到BeanDefinitionRegistry類型的 registry 對象中。實(shí)現(xiàn)接口ImportSelector這種情況下又?jǐn)U展了 DeferredImportSelector 接口的情況,該接口用來實(shí)現(xiàn)BeanDefinition的延遲注入功能更。DeferredImportSelector接口擴(kuò)展了ImportSelector接口,并且其中有個內(nèi)部接口 Group,如果某個@Import注解的value類實(shí)現(xiàn)了DeferredImportSelector接口并且也實(shí)現(xiàn)了該接口的內(nèi)部類Group接口,則表面此實(shí)現(xiàn)類需要延遲處理。如果是需要延遲處理,則會把ImportSelector 實(shí)例selector 組裝成
DeferredImportSelectorHolder 對象添加到 deferredImportSelectors集合中,處理邏輯源碼位置: org.springframework.context.annotation.ConfigurationClassParser.DeferredImportSelectorHandler#handle;關(guān)鍵代碼如下,

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接口的實(shí)現(xiàn)邏輯會在
org.springframework.context.annotation.ConfigurationClassParser#parse方法中調(diào)用,具體代碼在this.deferredImportSelectorHandler.process()中,關(guān)鍵代碼如下,

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);
            // 具體的執(zhí)行邏輯
            handler.processGroupImports();
        }
    }
    finally {
        this.deferredImportSelectors = new ArrayList<>();
    }
}

在processGroupImports()方法中,先通過grouping.getImports()拿到需要自動裝配的Group.Entry(封裝了全類名)對象集合,然后通過processImports()方法根據(jù)Entry類名字符串進(jìn)行創(chuàng)建SourceClass類(該類可以通過asConfigClass()方法轉(zhuǎn)成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()方法中主要執(zhí)行具體的實(shí)現(xiàn)類的process方法和selectImports()方法(如果是
AutoConfigurationImportSelector類,則調(diào)用org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process和org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#selectImports,兩個方法的具體類容請看2.2.2章節(jié)的說明),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.實(shí)現(xiàn)了
ImportBeanDefinitionRegistrar.class接口的場景;會先創(chuàng)建ImportBeanDefinitionRegistrar 實(shí)例類 registrar,再把 registrar 添加到 configClass 的 importBeanDefinitionRegistrars中,接口的registerBeanDefinitions方法的調(diào)用是在 org.springframework.context.annotation.ConfigurationClassPostProcessor#processConfigBeanDefinitions方法里的this.reader.loadBeanDefinitions(configClasses)代碼中。具體執(zhí)行語句loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());關(guān)鍵代碼如下,

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.沒有實(shí)現(xiàn)以上兩接口的普通類,會直接調(diào)用
org.springframework.context.annotation.ConfigurationClassParser#processImports里面的processConfigurationClass方法,把當(dāng)前configClass添加至 configurationClasses 集合中。configurationClasses集合中的對象最終會被注冊到BeanDefinitionRegistry類型的 registry 對象中。

2.@SpringApplication注解分析

? @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) })

2.1@SpringBootConfiguration

? 配置注解,包含了@Configuration注解,表明是配置類。

2.2@EnableAutoConfiguration

? 自動裝配注解,主要邏輯是:根據(jù) EnableAutoConfiguration 類型從META-INF/spring.factories 文件加載需要自動裝配的類,并注入到Spring容器中。它包括了@AutoConfigurationPackage注解和一個@Import(
AutoConfigurationImportSelector.class)注解。代碼如下,

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

2.2.1@AutoConfigurationPackage

? 注冊名為
org.springframework.boot.autoconfigure.AutoConfigurationPackages ,BeanClass為BasePackages.class 的GenericBeanDefinition 到 BeanDefinitionRegistry 中,通過@Import 注解實(shí)現(xiàn)注入功能,代碼如下,

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


AutoConfigurationPackages.Registrar.class實(shí)現(xiàn)了ImportBeanDefinitionRegistrar接口 ,所以在Spring容器初始化的過程中會調(diào)用它的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));
    }
}

2.2.2@Import(AutoConfigurationImportSelector.class)

? 自動裝配關(guān)鍵邏輯,先從META-INF/spring.factories 文件加載類型值為 EnableAutoConfiguration的字符串集合,再通過過濾,生成需要自動裝配的類,最后注入到Spring容器中。
AutoConfigurationImportSelector實(shí)現(xiàn)了DeferredImportSelector接口并且內(nèi)部也實(shí)現(xiàn)了DeferredImportSelector.Group接口,所以在Spring容器初始化的過程中會調(diào)用


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文件中獲取自動裝配的元數(shù)據(jù),
// 里面保存了加載類是否自動裝配的條件 ,
// 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);
// 循環(huán)遍歷 自動裝配類對象 的自動裝配類字符串 ,添加到 this.entries
for (String importClassName : autoConfigurationEntry.getConfigurations()) {
    this.entries.putIfAbsent(importClassName, annotationMetadata);
}


getAutoConfigurationMetadata() 方法主要邏輯是:從META-INF/spring-autoconfigure-metadata.properties文件中獲取自動裝配的元數(shù)據(jù),里面保存了自動加載類是否符合自動裝配的前置條件,比較熟悉的有ConditionalOnClass和ConditionalOnBean,文件相關(guān)內(nèi)容如下:

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;
    }
    // 獲取注解元數(shù)據(jù)的屬性
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
    // 從spring.factories 文件中獲取key為 EnableAutoConfiguration 的配置類字符串列表
    List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
    // 去掉重復(fù)的 自動裝配類字符串
    configurations = removeDuplicates(configurations);
    // 根據(jù)注解元數(shù)據(jù)獲取 需要排除的類名
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    // 檢查排除的類名
    checkExcludedClasses(configurations, exclusions);
    // 根據(jù)排除的類名進(jìn)行排除
    configurations.removeAll(exclusions);
    // 從spring.factories 文件中獲取key為 AutoConfigurationImportFilter 的配置對象進(jìn)行過濾
    // 過濾規(guī)則從 getAutoConfigurationMetadata() 返回類的數(shù)據(jù)中獲取
    configurations = filter(configurations, autoConfigurationMetadata);
    // 執(zhí)行導(dǎo)入配置類的監(jiān)聽事件
    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 對應(yīng)的實(shí)現(xiàn)類字符串為

# 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(需要自動裝配的包裝實(shí)體類) 對象集合,代碼如下,
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 注解的分析過程需要結(jié)合@Import注解的過程來看。

2.2.3@ComponentScan

? 組件掃描注解,用來配置自動掃描包路徑。如果沒有配置路徑,則掃描主配置類命名空間下的所有包和類。源碼分析, SpringBoot

分享到:
標(biāo)簽:SpringBoot
用戶無頭像

網(wǎng)友整理

注冊時間:

網(wǎng)站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運(yùn)動步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績評定2018-06-03

通用課目體育訓(xùn)練成績評定