java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot自动装配

详解SpringBoot启动代码和自动装配源码分析

作者:bei_er

这篇文章主要介绍了SpringBoot启动代码和自动装配源码分析,使用SpringBoot很简单,在主类中添加一个@SpringBootApplication,以及调用SpringApplication.run()并传入主类,本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下

​随着互联网的快速发展,各种组件层出不穷,需要框架集成的组件越来越多。每一种组件与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

2.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 对象中。

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

​自动装配注解,主要逻辑是:根据 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 注解实现注入功能,代码如下,

@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));
    }
}
2.2.2@Import(AutoConfigurationImportSelector.class)

​自动装配关键逻辑,先从META-INF/spring.factories 文件加载类型值为 EnableAutoConfiguration的字符串集合,再通过过滤,生成需要自动装配的类,最后注入到Spring容器中。AutoConfigurationImportSelector实现了DeferredImportSelector接口并且内部也实现了DeferredImportSelector.Group接口,所以在Spring容器初始化的过程中会调用

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

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,\
// 省略

2.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注解的过程来看。

2.2.3@ComponentScan

​组件扫描注解,用来配置自动扫描包路径。如果没有配置路径,则扫描主配置类命名空间下的所有包和类。

到此这篇关于SpringBoot启动代码和自动装配源码分析的文章就介绍到这了,更多相关SpringBoot自动装配内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文