Spring Boot - 启动引导

1. SpringBootApplication

/**
 * ......
 * @since 1.2.0
 */
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
                                 @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication

由文档注释可见,它是来自 SpringBoot1.2.0,其实在 SpringBoot1.1 及以前的版本,在启动类上标注的注解应该是三个:@Configuration + @EnableAutoConfiguration + @ComponentScan,只不过从1.2以后 SpringBoot 帮我们整合起来了。

文档注释原文翻译:

Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.

标识了一个配置类,这个配置类上声明了一个或多个 @Bean 的方法,并且它会触发自动配置和组件扫描。

这是一个很方便的注解,它等价于同时标注 @Configuration + @EnableAutoConfiguration + @ComponentScan

文档注释已经描述的很详细:它是一个组合注解,包括3个注解。标注它之后就会触发自动配置(@EnableAutoConfiguration)和组件扫描(@ComponentScan)。

至于这几个注解分别都起什么作用,咱们来一个一个看。

2. @ComponentScan

这个注解咱们在 SpringFramework 中有接触过,它可以指定包扫描的根路径,让 SpringFramework 来扫描指定包及子包下的组件,也可以不指定路径,默认扫描当前配置类所在包及子包里的所有组件(其实这就解释了为什么 SpringBoot 的启动类要放到所有类所在包的最外层)。

不过在上面的声明中有显式的指定了两个过滤条件:

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

这两个过滤器估计有猫腻,咱还得研究一下它们。

2.1 TypeExcludeFilter

文档注释原文翻译:

Provides exclusion TypeFilters that are loaded from the BeanFactory and automatically applied to SpringBootApplication scanning. Can also be used directly with @ComponentScan as follows:

Implementations should provide a subclass registered with BeanFactory and override the match(MetadataReader, MetadataReaderFactory) method. They should also implement a valid hashCode and equals methods so that they can be used as part of Spring test's application context caches. Note that TypeExcludeFilters are initialized very early in the application lifecycle, they should generally not have dependencies on any other beans. They are primarily used internally to support spring-boot-test.

提供从 BeanFactory 加载并自动应用于 @SpringBootApplication 扫描的排除 TypeFilter

实现应提供一个向 BeanFactory 注册的子类,并重写 match(MetadataReader, MetadataReaderFactory) 方法。它们还应该实现一个有效的 hashCodeequals 方法,以便可以将它们用作Spring测试的应用程序上下文缓存的一部分。

注意,TypeExcludeFilters 在应用程序生命周期的很早就初始化了,它们通常不应该依赖于任何其他bean。它们主要在内部用于支持 spring-boot-test

 @ComponentScan(excludeFilters = @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class))

从文档注释中大概能看出来,它是给了一种扩展机制,能让我们向IOC容器中注册一些自定义的组件过滤器,以在包扫描的过程中过滤它们

这种Filter的核心方法是 match 方法,它实现了过滤的判断逻辑:

public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
    throws IOException {
    if (this.beanFactory instanceof ListableBeanFactory && getClass() == TypeExcludeFilter.class) {
        Collection<TypeExcludeFilter> delegates = ((ListableBeanFactory) this.beanFactory)
            .getBeansOfType(TypeExcludeFilter.class).values();
        for (TypeExcludeFilter delegate : delegates) {
            if (delegate.match(metadataReader, metadataReaderFactory)) {
                return true;
            }
        }
    }
    return false;
}

注意看if结构体中的第一句,它会从 BeanFactory (可以暂时理解成IOC容器)中获取所有类型为 TypeExcludeFilter 的组件,去执行自定义的过滤方法。

由此可见,TypeExcludeFilter 的作用是做扩展的组件过滤

2.2 AutoConfigurationExcludeFilter

看这个类名,总感觉跟自动配置相关,还是看一眼它的源码:

public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
    throws IOException {
    return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader);
}

private boolean isConfiguration(MetadataReader metadataReader) {
    return metadataReader.getAnnotationMetadata().isAnnotated(Configuration.class.getName());
}

private boolean isAutoConfiguration(MetadataReader metadataReader) {
    return getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName());
}

protected List<String> getAutoConfigurations() {
    if (this.autoConfigurations == null) {
        this.autoConfigurations = SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,
                                                                         this.beanClassLoader);
    }
    return this.autoConfigurations;
}

它的 match 方法要判断两个部分:是否是一个配置类,是否是一个自动配置类。其实光从方法名上也就看出来了,下面的方法是其调用实现,里面有一个很关键的机制:SpringFactoriesLoader.loadFactoryNames,我们留到后面再解释。

3. @SpringBootConfiguration

@Configuration
public @interface SpringBootConfiguration

文档注释原文翻译:

Indicates that a class provides Spring Boot application @Configuration . Can be used as an alternative to the Spring's standard @Configuration annotation so that configuration can be found automatically (for example in tests).

Application should only ever include one @SpringBootConfiguration and most idiomatic Spring Boot applications will inherit it from @SpringBootApplication.

标识一个类作为 SpringBoot 的配置类,它可以是Spring原生的 @Configuration 的一种替换方案,目的是这个配置可以被自动发现。

应用应当只在主启动类上标注 @SpringBootConfiguration,大多数情况下都是直接使用 @SpringBootApplication

从文档注释以及它的声明上可以看出,它被 @Configuration 标注,说明它实际上是标注配置类的,而且是标注主启动类的。

3.1 @Configuration的作用

@Configuration 标注的类,会被 Spring 的IOC容器认定为配置类。

一个被 @Configuration 标注的类,相当于一个 applicationContext.xml 的配置文件。

例如:声明一个类,并标注 @Configuration 注解:

@Configuration
public class ConfigurationDemo {
    @Bean
    public Date currentDate() {
        return new Date();
    }
}

上述注册Bean的方式类比于xml:

<bean id="currentDate" class="java.util.Date"/>

之后使用注解启动方式,初始化一个IOC容器,并打印IOC容器中的所有bean的name:

public class MainApp {
    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
        String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
        Stream.of(beanDefinitionNames).forEach(System.out::println);
    }
}

输出结果:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
configurationDemo
currentDate

可以发现组件,以及配置类本身被成功加载。

3.2 @SpringBootConfiguration的附加作用

借助IDEA搜索 @SpringBootConfiguration 的出现位置,发现除了 @SpringBootApplication 外,只有一个位置使用了它:

发现是一个测试包中的usage(默认的 SpringInitializer 会把 spring-boot-starter-test 一起带进来,故可以搜到这个usage。如果小伙伴手动使用Maven创建 SpringBoot 应用且没有导入 spring-boot-start-test 依赖,则这个usage都不会搜到)。

它的作用我们不剖析源码了(毕竟作为刚开始就看那么复杂的东西属实是会把你吓跑),我们来翻看 SpringBoot 的官方文档,发现通篇只有两个位置提到了 @SpringBootConfiguration,还真有一个跟测试相关:

docs.spring.io/spring-boot…

第三段中有对 @SpringBootConfiguration 的描述:

The search algorithm works up from the package that contains the test until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration. As long as you structured your code in a sensible way, your main configuration is usually found.

搜索算法从包含测试的程序包开始工作,直到找到带有 @SpringBootApplication@SpringBootConfiguration 标注的类。只要您以合理的方式对代码进行结构化,通常就可以找到您的主要配置。

这很明显是解释了 SpringBoot 主启动类与测试的关系,标注 @SpringBootApplication@SpringBootConfiguration 的主启动类会被 Spring测试框架 的搜索算法找到。回过头看上面的截图,引用 @SpringBootConfiguration 的方法恰好叫 getOrFindConfigurationClasses,与文档一致。

至此,@SpringBootConfiguration 的作用解析完毕。

4. SpringFramework的手动装配

在原生的 SpringFramework 中,装配组件有三种方式:

  • 使用模式注解 @Component 等(Spring2.5+)

  • 使用配置类 @Configuration@Bean (Spring3.0+)

  • 使用模块装配 @EnableXXX@Import (Spring3.1+)

其中使用 @Component 及衍生注解很常见,咱开发中常用的套路,不再赘述。

但模式注解只能在自己编写的代码中标注,无法装配jar包中的组件。为此可以使用 @Configuration@Bean,手动装配组件(如上一篇的 @Configuration 示例)。

但这种方式一旦注册过多,会导致编码成本高,维护不灵活等问题。

SpringFramework 提供了模块装配功能,通过给配置类标注 @EnableXXX 注解,再在注解上标注 @Import 注解,即可完成组件装配的效果。

下面介绍模块装配的使用方式。

4.1 @EnableXXX与@Import的使用

创建几个颜色的实体类,如Red,Yellow,Blue,Green,Black等。

新建 @EnableColor注解,并声明 @Import(注意注解上有三个必须声明的元注解)

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

@Import 可以传入四种类型:普通类、配置类、ImportSelector 的实现类,ImportBeanDefinitionRegistrar 的实现类。具体如文档注释中描述:

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

value中写的很明白了,可以导入配置类**ImportSelector** 的实现类**ImportBeanDefinitionRegistrar** 的实现类,或者普通类

下面介绍 @Import 的用法。

4.1.1 导入普通类

直接在 @Import 注解中标注Red类:

@Import({Red.class})
public @interface EnableColor {
    
}

之后启动类标注 @EnableColor ,引导启动IOC容器:

@EnableColor
@Configuration
public class ColorConfiguration {
    
}

public class App {
    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ColorConfiguration.class);
        String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
        Stream.of(beanDefinitionNames).forEach(System.out::println);
    }
}

控制台打印:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
colorConfiguration
com.example.demo.enablexxx.Red

可见Red类已经被注册。

4.1.2 导入配置类

新建 ColorRegistrarConfiguration,并标注 @Configuration

@Configuration
public class ColorRegistrarConfiguration {
    
    @Bean
    public Yellow yellow() {
        return new Yellow();
    }
    
}

之后在 @EnableColor@Import 注解中加入 ColorRegistrarConfiguration

@Import({Red.class, ColorRegistrarConfiguration.class})
public @interface EnableColor {
    
}

重新启动IOC容器,打印结果:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
colorConfiguration
com.example.demo.enablexxx.Red
com.example.demo.enablexxx.ColorRegistrarConfiguration
yellow

可见配置类 ColorRegistrarConfigurationYellow 都已注册到IOC容器中。

4.1.3 导入ImportSelector

新建 ColorImportSelector,实现 ImportSelector 接口:

public class ColorImportSelector implements ImportSelector {
    
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[] {Blue.class.getName(), Green.class.getName()};
    }
    
}

之后在 @EnableColor@Import 注解中加入 ColorImportSelector

@Import({Red.class, ColorRegistrarConfiguration.class, ColorImportSelector.class})
public @interface EnableColor {
    
}

重新启动IOC容器,打印结果:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
colorConfiguration
com.example.demo.enablexxx.Red
com.example.demo.enablexxx.ColorRegistrarConfiguration
yellow
com.example.demo.enablexxx.Blue
com.example.demo.enablexxx.Green

ColorImportSelector 没有注册到IOC容器中,两个新的颜色类被注册。

4.1.4 导入ImportBeanDefinitionRegistrar

新建 ColorImportBeanDefinitionRegistrar,实现 ImportBeanDefinitionRegistrar 接口:

public class ColorImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition("black", new RootBeanDefinition(Black.class));
    }
    
}

之后在 @EnableColor @Import 注解中加入 ColorImportBeanDefinitionRegistrar

@Import({Red.class, ColorRegistrarConfiguration.class, ColorImportSelector.class, ColorImportBeanDefinitionRegistrar.class})
public @interface EnableColor {
    
}

重新启动IOC容器,打印结果:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
colorConfiguration
com.example.demo.enablexxx.Red
com.example.demo.enablexxx.ColorRegistrarConfiguration
yellow
com.example.demo.enablexxx.Blue
com.example.demo.enablexxx.Green
black

由于在注册Black的时候要指定Bean的id,而上面已经标明了使用 "black" 作为id,故打印的 beanDefinitionName 就是black。

以上就是 SpringFramework 的手动装配方法。那 SpringBoot 又是如何做自动装配的呢?

5. SpringBoot的自动装配

SpringBoot的自动配置完全由 @EnableAutoConfiguration 开启。

@EnableAutoConfiguration 的内容:

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration

文档注释原文翻译:(文档注释很长,但句句精华)

Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined. For example, if you have tomcat-embedded.jar on your classpath you are likely to want a TomcatServletWebServerFactory (unless you have defined your own ServletWebServerFactory bean).

When using SpringBootApplication, the auto-configuration of the context is automatically enabled and adding this annotation has therefore no additional effect.

Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration. You can always manually exclude() any configuration that you never want to apply (use excludeName() if you don't have access to them). You can also exclude them via the spring.autoconfigure.exclude property. Auto-configuration is always applied after user-defined beans have been registered.

The package of the class that is annotated with @EnableAutoConfiguration, usually via @SpringBootApplication, has specific significance and is often used as a 'default'. For example, it will be used when scanning for @Entity classes. It is generally recommended that you place @EnableAutoConfiguration (if you're not using @SpringBootApplication) in a root package so that all sub-packages and classes can be searched.

Auto-configuration classes are regular Spring Configuration beans. They are located using the SpringFactoriesLoader mechanism (keyed against this class). Generally auto-configuration beans are @Conditional beans (most often using @ConditionalOnClass and @ConditionalOnMissingBean annotations).

启用Spring-ApplicationContext的自动配置,并且会尝试猜测和配置您可能需要的Bean。通常根据您的类路径和定义的Bean来应用自动配置类。例如,如果您的类路径上有 tomcat-embedded.jar,则可能需要 TomcatServletWebServerFactory (除非自己已经定义了 ServletWebServerFactory 的Bean)。

使用 @SpringBootApplication 时,将自动启用上下文的自动配置,因此再添加该注解不会产生任何其他影响。

自动配置会尝试尽可能地智能化,并且在您定义更多自定义配置时会自动退出(被覆盖)。您始终可以手动排除掉任何您不想应用的配置(如果您无法访问它们,请使用 excludeName() 方法),您也可以通过 spring.autoconfigure.exclude 属性排除它们。自动配置始终在注册用户自定义的Bean之后应用。

通常被 @EnableAutoConfiguration 标注的类(如 @SpringBootApplication)的包具有特定的意义,通常被用作“默认值”。例如,在扫描@Entity类时将使用它。通常建议您将 @EnableAutoConfiguration(如果您未使用 @SpringBootApplication)放在根包中,以便可以搜索所有包及子包下的类。

自动配置类也是常规的Spring配置类。它们使用 SpringFactoriesLoader 机制定位(针对此类)。通常自动配置类也是 @Conditional Bean(最经常的情况下是使用 @ConditionalOnClass@ConditionalOnMissingBean 标注)。

文档注释已经写得很明白了,后续源码会一点一点体现文档注释中描述的内容。

@EnableAutoConfiguration 是一个组合注解,分别来看:

6.1 @AutoConfigurationPackage

@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage

文档注释原文翻译:

Indicates that the package containing the annotated class should be registered with AutoConfigurationPackages.

表示包含该注解的类所在的包应该在 AutoConfigurationPackages 中注册。

咱从一开始学 SpringBoot 就知道一件事:主启动类必须放在所有自定义组件的包的最外层,以保证Spring能扫描到它们。由此可知是它起的作用。

它的实现原理是在注解上标注了 @Import,导入了一个 AutoConfigurationPackages.Registrar

6.1.1 AutoConfigurationPackages.Registrar

/**
* {@link ImportBeanDefinitionRegistrar} to store the base package from the importing
* configuration.
*/
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));
    }
    
}

文档注释原文翻译:

ImportBeanDefinitionRegistrar to store the base package from the importing configuration.

用于保存导入的配置类所在的根包。

很明显,它就是实现把主配置所在根包保存起来以便后期扫描用的。分析源码:

Registrar 实现了 ImportBeanDefinitionRegistrar 接口,它向IOC容器中要手动注册组件。

在重写的 registerBeanDefinitions 方法中,它要调用外部类 AutoConfigurationPackages 的register方法。

且不说这个方法的具体作用,看传入的参数:new PackageImport(metadata).getPackageName()

它实例化的 PackageImport 对象的构造方法:

PackageImport(AnnotationMetadata metadata) {
    this.packageName = ClassUtils.getPackageName(metadata.getClassName());
}

它取了一个 metadata 的所在包名。那 metadata 又是什么呢?

翻看 ImportBeanDefinitionRegistrar的文档注释:

public interface ImportBeanDefinitionRegistrar {
    /**
     * ......
     * @param importingClassMetadata annotation metadata of the importing class
     * @param registry current bean definition registry
     */
    void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry);
}

注意 importingClassMetadata 的参数说明:导入类的注解元数据

它实际代表的是被 @Import 标记的类的信息。

那在 SpringBoot 的主启动类中,被标记的肯定就是最开始案例里的 DemoApplication

也就是说它是 DemoApplication 的类信息,那获取它的包名就是获取主启动类的所在包。

拿到这个包有什么意义呢?不清楚,那就回到那个 Registrar 中,看它调用的 register 方法都干了什么:

6.1.2 register方法

private static final String BEAN = AutoConfigurationPackages.class.getName();

public static void register(BeanDefinitionRegistry registry, String... packageNames) {
    // 判断 BeanFactory 中是否包含 AutoConfigurationPackages
    if (registry.containsBeanDefinition(BEAN)) {
        BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
        ConstructorArgumentValues constructorArguments = beanDefinition.getConstructorArgumentValues();
        // addBasePackages:添加根包扫描包
        constructorArguments.addIndexedArgumentValue(0, addBasePackages(constructorArguments, packageNames));
    }
    else {
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(BasePackages.class);
        beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, packageNames);
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(BEAN, beanDefinition);
    }
}

划重点:它要判断当前IOC容器中是否包含 AutoConfigurationPackages 。如果有,就会拿到刚才传入的包名,设置到一个 basePackage 里面!basePackage 的意义很明显是根包。

换句话说,它要取主启动类所在包及子包下的组件

不过,在实际Debug时,并不是走的上面流程,因为 AutoConfigurationPackages 对应的 Bean 还没有创建,所以走的下面的 else 部分,直接把主启动类所在包放入 BasePackages 中,与上面 if 结构中最后一句一样,都是调用 addIndexedArgumentValue 方法。那这个 BasePackages 中设置了构造器参数,一定会有对应的成员:

static final class BasePackages {
    
    private final List<String> packages;
    
    BasePackages(String... names) {
        List<String> packages = new ArrayList<>();
        for (String name : names) {
            if (StringUtils.hasText(name)) {
                packages.add(name);
            }
        }
        this.packages = packages;
    }

果然,它有一个专门的成员存放这些 basePackage 。

6.1.3 basePackage的作用

如果这个 basePackage 的作用仅仅是提供给 SpringFramework 和 SpringBoot 的内部使用,那这个设计似乎有一点多余。回想一下,SpringBoot 的强大之处,有一点就是整合第三方技术可以非常的容易。以咱最熟悉的 MyBatis 为例,咱看看 basePackage 如何在整合第三方技术时被利用。

引入 mybatis-spring-boot-starter 依赖后,可以在 IDEA 中打开 MyBatisAutoConfiguration 类。在这个配置类中,咱可以找到这样一个组件:AutoConfiguredMapperScannerRegistrar

public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {
    
    private BeanFactory beanFactory;
    
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        if (!AutoConfigurationPackages.has(this.beanFactory)) {
            logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
            return;
        }
        logger.debug("Searching for mappers annotated with @Mapper");
        
        List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
        // logger ......
        // 注册Mapper ......
    }

看类名也能看的出来,它是扫描 Mapper 并注册到 IOC 容器的 ImportBeanDefinitionRegistrar !那这里头,取扫描根包的动作就是 AutoConfigurationPackages.get(this.beanFactory) ,由此就可以把事先准备好的 basePackages 都拿出来,之后进行扫描。

到这里,就呼应了文档注释中的描述,也解释了为什么 SpringBoot 的启动器一定要在所有类的最外层

6. SpringBoot的自动装配

6.2 @Import(AutoConfigurationImportSelector.class)

根据上一章节的基础,看到这个也不难理解,它导入了一个 ImportSelector,来向容器中导入组件。

导入的组件是:AutoConfigurationImportSelector

6.2.1 AutoConfigurationImportSelector

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
		ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered

文档注释原文翻译:

DeferredImportSelector to handle auto-configuration. This class can also be subclassed if a custom variant of @EnableAutoConfiguration is needed.

DeferredImportSelector 处理自动配置。如果需要自定义扩展 @EnableAutoConfiguration,则也可以编写该类的子类。

咱能看出来它是 ImportSelector , 可它又特别提到了 DeferredImportSelector,它又是什么呢?

6.2.2 DeferredImportSelector

public interface DeferredImportSelector extends ImportSelector

它是 ImportSelector 的子接口,它的文档注释原文和翻译:

A variation of ImportSelector that runs after all @Configuration beans have been processed. This type of selector can be particularly useful when the selected imports are @Conditional . Implementations can also extend the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation to indicate a precedence against other DeferredImportSelectors . Implementations may also provide an import group which can provide additional sorting and filtering logic across different selectors.

ImportSelector 的一种扩展,在处理完所有 @Configuration 类型的Bean之后运行。当所选导入为 @Conditional 时,这种类型的选择器特别有用。

实现类还可以扩展 Ordered 接口,或使用 @Order 注解来指示相对于其他 DeferredImportSelector 的优先级。

实现类也可以提供导入组,该导入组可以提供跨不同选择器的其他排序和筛选逻辑。

由此我们可以知道,DeferredImportSelector 的执行时机,是 **@Configuration** 注解中的其他逻辑被处理完毕之后(包括对 **@ImportResource****@Bean** 这些注解的处理)再执行,换句话说,**DeferredImportSelector** 的执行时机比 **ImportSelector** 更晚

回到 AutoConfigurationImportSelector,它的核心部分,就是 ImportSelectorselectImport 方法:

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    }
    
    AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
        .loadMetadata(this.beanClassLoader);
    // 加载自动配置类
    AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata, 
                                                                              annotationMetadata);
    return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}

关键的源码在 getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata)

【小伙伴在断点调试时,请把断点打在 getAutoConfigurationEntry 方法的内部实现中,不要直接打在这个 selectImports 方法!!!】

6.2.3 getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata)

/**
* Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
* of the importing {@link Configuration @Configuration} class.
* 
* 根据导入的@Configuration类的AnnotationMetadata返回AutoConfigurationImportSelector.AutoConfigurationEntry。
*/
protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
                                                           AnnotationMetadata annotationMetadata) {
    if (!isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    }
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
    // 【核心】加载候选的自动配置类
    List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
    configurations = removeDuplicates(configurations);
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    checkExcludedClasses(configurations, exclusions);
    configurations.removeAll(exclusions);
    configurations = filter(configurations, autoConfigurationMetadata);
    fireAutoConfigurationImportEvents(configurations, exclusions);
    return new AutoConfigurationEntry(configurations, exclusions);
}

这个方法里有一个非常关键的集合:configurations(最后直接拿他来返回出去了,给 selectImports 方法转成 String[])。

既然最后拿它返回出去,必然它是导入其他组件的核心。

这个 configurations 集合的数据,都是通过 getCandidateConfigurations 方法来获取:

protected Class<?> getSpringFactoriesLoaderFactoryClass() {
    return EnableAutoConfiguration.class;
}

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    // SPI机制加载自动配置类
    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;
}

这个方法又调用了 SpringFactoriesLoader.loadFactoryNames 方法,传入的Class就是 @EnableAutoConfiguration

6.2.4 SpringFactoriesLoader.loadFactoryNames

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    //     ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
    return loadSpringFactories(classLoader).getOrDefault(factoryClassName, 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 factoryClassName = ((String) entry.getKey()).trim();
                for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                    result.add(factoryClassName, factoryName.trim());
                }
            }
        }
        cache.put(classLoader, result);
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                                           FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

源码中使用 classLoader 去加载了指定常量路径下的资源: FACTORIES_RESOURCE_LOCATION ,而这个常量指定的路径实际是:META-INF/spring.factories

这个文件在 spring-boot-autoconfiguration 包下可以找到。

spring-boot-autoconfiguration 包下 META-INF/spring.factories 节选:

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# 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,\
......

之后拿到这个资源文件,以 Properties 的形式加载,并取出 org.springframework.boot.autoconfigure.EnableAutoConfiguration 指定的所有自动配置类(是一个很大的字符串,里面都是自动配置类的全限定类名),装配到IOC容器中,之后自动配置类就会通过 ImportSelector@Import 的机制被创建出来,之后就生效了。

这也就解释了为什么 即便没有任何配置文件,SpringBoot的Web应用都能正常运行

6.2.5 【总结规律】

从上面的 Properties 中发现,所有配置的 EnableAutoConfiguration 的自动配置类,都以 AutoConfiguration 结尾!由此规律,以后我们要了解一个 SpringBoot 的模块或者第三方集成的模块时,就可以大胆猜测基本上一定会有 XXXAutoConfiguration 类出现

6.3 【扩展】SpringBoot使用的工厂机制

SpringBoot 在非常多的位置都利用类似于上面 “通过读取 spring.factories 加载一组预先配置的类” 的机制,而这个机制的核心源码来自 SpringFactoriesLoader 。这一章节我们来详细了解一下这个类,对于后续 SpringBoot 的应用启动过程的源码阅读和原理的理解都有所帮助。

package org.springframework.core.io.support;

/**
* ......
*
* @since 3.2
*/
public final class SpringFactoriesLoader

我们发现它不是来自 SpringBoot,而是在 SpringFramework3.2 就已经有了的类。它的文档注释原文翻译:

General purpose factory loading mechanism for internal use within the framework. SpringFactoriesLoader loads and instantiates factories of a given type from "META-INF/spring.factories" files which may be present in multiple JAR files in the classpath. The spring.factories file must be in Properties format, where the key is the fully qualified name of the interface or abstract class, and the value is a comma-separated list of implementation class names. For example: example.MyService=example.MyServiceImpl1,example.MyServiceImpl2 where example.MyService is the name of the interface, and MyServiceImpl1 and MyServiceImpl2 are two implementations.

它是一个框架内部内部使用的通用工厂加载机制。

SpringFactoriesLoaderMETA-INF/spring.factories 文件中加载并实例化给定类型的工厂,这些文件可能存在于类路径中的多个jar包中。spring.factories 文件必须采用 properties 格式,其中key是接口或抽象类的全限定名,而value是用逗号分隔的实现类的全限定类名列表。

例如:example.MyService=example.MyServiceImpl1,example.MyServiceImpl2

其中 example.MyService 是接口的名称,而 MyServiceImpl1MyServiceImpl2 是两个该接口的实现类。

到这里已经能够发现,这个思路跟Java原生的SPI非常类似。

6.3.1 【扩展】Java的SPI

SPI全称为 Service Provider Interface,是jdk内置的一种服务提供发现机制。简单来说,它就是一种动态替换发现的机制。

SPI规定,所有要预先声明的类都应该放在 META-INF/services 中。配置的文件名是接口/抽象类的全限定名,文件内容是抽象类的子类或接口的实现类的全限定类名,如果有多个,借助换行符,一行一个。

具体使用时,使用jdk内置的 ServiceLoader 类来加载预先配置好的实现类。

举个例子:

META-INF/services 中声明一个文件名为 com.linkedbear.boot.demo.SpiDemoInterface 的文件,文件内容为:

com.linkedbear.boot.demo.SpiDemoInterfaceImpl

com.linkedbear.boot.demo 包下新建一个接口,类名必须跟上面配置的文件名一样:SpiDemoInterface

在接口中声明一个 test() 方法:

public interface SpiDemoInterface {
    void test();
}

接下来再新建一个类 SpiDemoInterfaceImpl,并实现 SpiDemoInterface

public class SpiDemoInterfaceImpl implements SpiDemoInterface {
    @Override
    public void test() {
        System.out.println("SpiDemoInterfaceImpl#test() run...");
    }
}

编写主运行类,测试效果:

public class App {
    public static void main(String[] args) {
        ServiceLoader<SpiDemoInterface> loaders = ServiceLoader.load(SpiDemoInterface.class);
        loaders.foreach(SpiDemoInterface::test);
    }
}

运行结果:

SpiDemoInterfaceImpl#test() run...

6.3.2 SpringFramework的SpringFactoriesLoader

SpringFramework 利用 SpringFactoriesLoader 都是调用 loadFactoryNames 方法:

/**
* Load the fully qualified class names of factory implementations of the
* given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
* class loader.
* @param factoryClass the interface or abstract class representing the factory
* @param classLoader the ClassLoader to use for loading resources; can be
* {@code null} to use the default
* @throws IllegalArgumentException if an error occurs while loading factory names
* @see #loadFactories
*/
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

文档注释原文翻译:

Load the fully qualified class names of factory implementations of the given type from "META-INF/spring.factories", using the given class loader.

使用给定的类加载器从 META-INF/spring.factories 中加载给定类型的工厂实现的全限定类名。

文档注释中没有提到接口、抽象类、实现类的概念,结合之前看到过的 spring.factories 文件,应该能意识到它只是key-value的关系

这么设计的好处:不再局限于接口-实现类的模式,key可以随意定义! (如上面的 org.springframework.boot.autoconfigure.EnableAutoConfiguration 是一个注解)

来看方法实现,第一行代码获取的是要被加载的接口/抽象类的全限定名,下面的 return 分为两部分:loadSpringFactoriesgetOrDefaultgetOrDefault 方法很明显是Map中的方法,不再解释,主要来详细看 loadSpringFactories 方法。

6.3.3 loadSpringFactories

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();

// 这个方法仅接收了一个类加载器
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 factoryClassName = ((String) entry.getKey()).trim();
                for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                    result.add(factoryClassName, factoryName.trim());
                }
            }
        }
        cache.put(classLoader, result);
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                                           FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

我们分段来看。

6.3.3.1 获取本地缓存

MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
    return result;
    }

进入方法后先从本地缓存中根据当前的类加载器获取是否有一个类型为 MultiValueMap<String, String> 的值,这个类型有些陌生,我们先看看这是个什么东西:

package org.springframework.util;

/**
 * Extension of the {@code Map} interface that stores multiple values.
 *
 * @since 3.0
 * @param <K> the key type
 * @param <V> the value element type
 */
public interface MultiValueMap<K, V> extends Map<K, List<V>>

发现它实际上就是一个 Map<K, List<V>>

那第一次从cache中肯定获取不到值,故下面的if结构肯定不进入,进入下面的try块。

6.3.3.2 加载spring.factories

Enumeration<URL> urls = (classLoader != null ?
                         classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                         ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();

这部分动作就是获取当前 classpath 下所有jar包中有的 spring.factories 文件,并将它们加载到内存中。

6.3.3.3 缓存到本地

while (urls.hasMoreElements()) {
    URL url = urls.nextElement();
    UrlResource resource = new UrlResource(url);
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    for (Map.Entry<?, ?> entry : properties.entrySet()) {
        String factoryClassName = ((String) entry.getKey()).trim();
        for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
            result.add(factoryClassName, factoryName.trim());
        }
    }
}
        cache.put(classLoader, result);

它拿到每一个文件,并用 Properties 方式加载文件,之后把这个文件中每一组键值对都加载出来,放入 MultiValueMap 中。

如果一个接口/抽象类有多个对应的目标类,则使用英文逗号隔开。StringUtils.commaDelimitedListToStringArray会将大字符串拆成一个一个的全限定类名。

整理完后,整个result放入cache中。下一次再加载时就无需再次加载 spring.factories 文件了。

最后更新于