SpringBoot源码解读与原理分析(五)SpringBoot的装配机制

时间:2024-02-23 06:58:36

文章目录

    • 2.5 Spring Boot的装配机制
      • 2.5.1 @ComponentScan
        • 2.5.1.1 @ComponentScan的基本使用方法
        • 2.5.1.2 TypeExcludeFilter(类型排除过滤器)
        • 2.5.1.3 AutoConfigurationExcludeFilter(自动配置类排除过滤器)
      • 2.5.2 @SpringBootConfiguration
      • 2.5.3 @EnableAutoConfiguration
        • 2.5.3.1 javadoc描述
        • 2.5.3.2 @AutoConfigurationPackage
          • (1)Registrar
          • (2)PackageImports
          • (3)register方法
          • (4)BasePackages
          • (5)保存SpringBoot应用的根包路径作用
        • 2.5.3.3 AutoConfigurationImportSelector
          • (1)AutoConfigurationGroup
          • (2)getAutoConfigurationEntry
      • 2.5.4 总结

前面三小节分别介绍了Spring Framewoek的模块装配、条件装配和SPI机制。下面正式进入Spring Boot的装配机制。

2.5 Spring Boot的装配机制

实际上,Spring Boot的自动装配是模块装配+条件装配+SPI机制的组合使用,而这一切都凝聚在Spring Boot主启动类的@SpringBootApplication注解上。

@SpringBootApplication注解是由三个注解组合而成的复合注解:

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

因此,主启动类标注@SpringBootApplication,会触发@EnableAutoConfiguration自动装配和@ComponentScan组件扫描。

2.5.1 @ComponentScan

@ComponentScan放在@SpringBootApplication中的意图:扫描主启动类所在包及其子包下的所有组件。
这也解释了为什么主启动类要放到所有类所在包的最外层。

2.5.1.1 @ComponentScan的基本使用方法

下面通过一个例子加以理解:
(1)创建Boss类和BossConfiguration类,两个类放在同一包下
两个类放在同一包下

@Component("aBoss")
public class Boss {
}
@Configuration
@ComponentScan
public class BossConfiguration {
}

通过@ComponentScan注解,SpringBoot会扫描BossConfiguration所在包及其子包的所有组件。由于Boss组件和BossConfiguration组件在同一包下,所以Boss组件将会组测到IOC容器中。

(2)测试

public class BossApp {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BossConfiguration.class);
        System.out.println("-------分割线-------");
        Stream.of(context.getBeanDefinitionNames()).forEach(System.out::println);
        System.out.println("-------分割线-------");
    }

}

输出结果(已省略一些内部组件打印,下同):

-------分割线-------
bossConfiguration
aBoss
-------分割线-------

(3)Boss类和BossConfiguration类放在同一个包下肯定是不合理的,所以调整一下位置,把BossConfiguration来放在其它目录下,如图:
两个类放在不同包下
此时的输出结果显示,Boss并没有注册到IOC容器:

-------分割线-------
bossConfiguration
-------分割线-------

(4)查看@ComponentScan的源码,可以找到几个常用的属性:

  • basePackages:定义扫描的包名,在没有定义的情况下,扫描当前包和其子包。
  • includeFilters:定义满足过滤器,只有满足过滤器条件的Bean才会注册。
  • excludeFilters:定义排除过滤器,满足过滤器条件的Bean会被排除注册。

在@ComponentScan加basePackages参数,指定Boss所在的包:

@Configuration
@ComponentScan(basePackages = "com.star.springboot.assemble.test01.pojo")
public class BossConfiguration {
}

此时的输出结果显示,Boss已经注册到IOC容器:

-------分割线-------
bossConfiguration
aBoss
-------分割线-------
2.5.1.2 TypeExcludeFilter(类型排除过滤器)

和平时使用不一样,@ComponentScan注解额外添加了两个过滤条件:

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

它的作用是,让开发者向IOC容器注册自定义的过滤器组件,在组件扫描过程中匹配自定义过滤器的规则,以过滤掉一些不需要的组件。

javadoc:
Implementations should provide a subclass registered with {@link BeanFactory} and override the {@link #match(MetadataReader, MetadataReaderFactory)} method.
TypeExcludeFilter的使用方法:在BeanFactory中注册一个子类,并重写match方法,SpringBoot会自动找到这些子类并调用它们。

【拓展】由FilterType源码可知,@ComponentScan不仅支持自定义过滤器组件(CUSTOM),还支持以注解(ANNOTATION)、类(ASSIGNABLE_TYPE)、AspectJ(ASPECTJ)、正则(REGEX)为线索进行过滤。

public enum FilterType {

	/**
	 * Filter candidates marked with a given annotation.
	 * @see org.springframework.core.type.filter.AnnotationTypeFilter
	 */
	ANNOTATION,

	/**
	 * Filter candidates assignable to a given type.
	 * @see org.springframework.core.type.filter.AssignableTypeFilter
	 */
	ASSIGNABLE_TYPE,

	/**
	 * Filter candidates matching a given AspectJ type pattern expression.
	 * @see org.springframework.core.type.filter.AspectJTypeFilter
	 */
	ASPECTJ,

	/**
	 * Filter candidates matching a given regex pattern.
	 * @see org.springframework.core.type.filter.RegexPatternTypeFilter
	 */
	REGEX,

	/** Filter candidates using a given custom
	 * {@link org.springframework.core.type.filter.TypeFilter} implementation.
	 */
	CUSTOM

}

下面继续通过上面的例子加以理解:

(1)注册自定义的过滤器组件:在上下文注册TypeExcludeFilter的子类,并重写match方法,match方法返回true则匹配,返回false则不匹配。SpringBoot会自动找到这些TypeExcludeFilter的子类并执行match方法。

public class MyTypeExcludeFilter extends TypeExcludeFilter {

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        System.out.println("自定义过滤器执行了...");
        return Boss.class.getName().equals(metadataReader.getClassMetadata().getClassName());
    }

}

(2)在@ComponentScan配置自定义过滤器组件

@Configuration
@ComponentScan(basePackages = "com.star.springboot.assemble.test01.pojo",
    excludeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, classes = MyTypeExcludeFilter.class)})
public class BossConfiguration {

}

(3)测试

-------分割线-------
bossConfiguration
-------分割线-------

输出结果显示,Boss没有注册到IOC容器,说明自定义的过滤器组件生效了。

(4)TypeExcludeFilter的核心逻辑

TypeExcludeFilter的底层实现:从BeanFactory中提取出所有类为TypeExcludeFilter的Bean,并缓存到本地(空间换时间的设计体现),后续在进行组件扫描时会依次调用这些TypeExcludeFilter对象,检查被扫描的类是否符合匹配规则。

符合规则的,不注册到IOC容器;不符合的才注册到IOC容器。

public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware {

    private BeanFactory beanFactory;

    private Collection<TypeExcludeFilter> delegates;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
        throws IOException {
        if (this.beanFactory instanceof ListableBeanFactory && getClass() == TypeExcludeFilter.class) {
            // 提取出所有TypeExcludeFilter并依次调用其match方法检查是否匹配
            for (TypeExcludeFilter delegate : getDelegates()) {
                if (delegate.match(metadataReader, metadataReaderFactory)) {
                    return true;
                }
            }
        }
        return false;
    }

    private Collection<TypeExcludeFilter> getDelegates() {
        Collection<TypeExcludeFilter> delegates = this.delegates;
        if (delegates == null) {
            // 从BeanFactory中提取所有类为TypeExcludeFilter的Bean
            delegates = ((ListableBeanFactory) this.beanFactory).getBeansOfType(TypeExcludeFilter.class).values();
            this.delegates = delegates;
        }
        return delegates;
    }

    // ...

}
2.5.1.3 AutoConfigurationExcludeFilter(自动配置类排除过滤器)
  • 被@Configuration注解标注的类是配置类。
  • 被spring.factories中的@EnableAutoConfiguration注解的配置类是自动配置类。
  • 作用:在组件扫描阶段过滤掉一些自动配置类。
  • AutoConfigurationExcludeFilter的源码:
public class AutoConfigurationExcludeFilter implements TypeFilter, BeanClassLoaderAware {

    private ClassLoader beanClassLoader;

    private volatile List<String> autoConfigurations;

    @Override
    public void setBeanClassLoader(ClassLoader beanClassLoader) {
        this.beanClassLoader = beanClassLoader;
    }

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

    private boolean isConfiguration(MetadataReader metadataReader) {
        // 检查是配置类的规则:是否被@Configuration注解修饰
        return metadataReader.getAnnotationMetadata().isAnnotated(Configuration.class.getName());
    }

    private boolean isAutoConfiguration(MetadataReader metadataReader) {
        // 检查是自动配置类的规则:是否被定义在spring.factories中的EnableAutoConfiguration中
        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;
    }

}

2.5.2 @SpringBootConfiguration

@SpringBootConfiguration其实很简单,本身仅组合了一个Spring Framework的@Configuration而已。换句话说,一个类标注了@SpringBootConfiguration,也就是标注了@Configuration,代表这个类是一个注解配置类。

@Configuration
public @interface SpringBootConfiguration

2.5.3 @EnableAutoConfiguration

@EnableAutoConfiguration是重头戏,承载了SpringBoot自动装配的灵魂。

2.5.3.1 javadoc描述

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.

第一段讲解注解本身的作用。
标注@EnableAutoConfiguration后,Spring上下文的自动装配机制将会启用,SpringBoot会尝试猜测和配置当前项目可能需要的Bean。自动配置类的使用通常基于项目类路径和定义的Bean。例如,如果在类路径下引用了tomcat-embedded.jar包,则SpringBoot会猜测当前项目很可能需要配置一个TomcatServletWebServerFactory(除非项目已经手动配置了一个ServletWebServerFactory)。标注@SpringBootApplication后,Spring上下文的自动装配会自动启用,所以再配置@EnableAutoConfiguration没有附加作用(也就是不需要再配置@EnableAutoConfiguration)。

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.

第二段讲解SpringBoot自动装配的机制和禁用方法。
SpringBoot自动装配会尽可能地智能化,并会在项目注册了更多自定义配置时自动退出(即被覆盖)。开发者可以手动排除任何不想使用的自动配置(使用exclude属性,或在无法访问时使用excludeName属性),还可以通过全局配置文件的spring.autoconfigure.exclude属性。自动配置总是在用户自定义的Bean被注册之后才进行。

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.

第三段讲解组件扫描的规则。
被@EnableAutoConfiguration或@SpringBootApplication标注的类,其所在包有特殊的含义,通常被定义为“默认值”。例如,当扫描被@Entity标注的类时会用到。通常建议,把@EnableAutoConfiguration标注在一个根包中的类,这个根包及其子包的所有组件都将被扫描。

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).

第四段讲解自动配置类与SPI机制的关系。
自动配置类本身也是常规的Spring配置类,只不过它们的加载是通过SpringFactoriesLoader机制(即SPI机制)。通常自动配置类也是条件配置类(被@Conditional系列注解标注,最常用的是@ConditionalOnClass和@ConditionalOnMissingBean注解)。

总结:标注@EnableAutoConfiguration后,会启用SpringBoot的自动装配,根据导入的依赖、上下文配置合理加载默认的自动配置。

@EnableAutoConfiguration本身也是一个组合注解,包含了两个注解:

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration
2.5.3.2 @AutoConfigurationPackage
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage

由以上源码可知,@AutoConfigurationPackage注解组合了一个@Import注解,导入了一个内部类AutoConfigurationPackages.Registrar。

@AutoConfigurationPackage的作用是,将主启动类所在的包记录下来,注册到AutoConfigurationPackages中。

在SpringBoot 2.3.0版本以前,@AutoConfigurationPackage注解没有任何属性,标注了该注解即确定了主启动类所在包(约定)。在SpringBoot 2.3.0版本以后,注解中多了两个属性,basePackages和basePackageClasses,它们可以手动指定应用的根包/根路径(配置)。如果没有手动指定,则仍然采用默认的主启动类所在包(约定大于配置)。

(1)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 PackageImports(metadata).getPackageNames().toArray(new     String[0]));
    }

    @Override
    public Set<Object> determineImports(AnnotationMetadata metadata) {
        return Collections.singleton(new PackageImports(metadata));
    }

}

由以上源码可知,Registrar本身是一个ImportBeanDefinitionRegistrar,以编程式配置向IOC容器注册bean对象,而这个对象正是主启动类的包路径(方法注释中说到:store the base package)。

再来关注一下registerBeanDefinitions方法,该方法直接调用register方法,第二个参数是由PackageImports导出的一个包名数组。

(2)PackageImports
PackageImports(AnnotationMetadata metadata) {
    AnnotationAttributes attributes = AnnotationAttributes
        .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false));
    List<String> packageNames = new ArrayList<>();
    // 先提取自定义的basePackages属性
    for (String basePackage : attributes.getStringArray("basePackages")) {
        packageNames.add(basePackage);
    }
    // 再提取自定义的basePackageClasses属性
    for (Class<?> basePackageClass : attributes.getClassArray("basePackageClasses")) {
        packageNames.add(basePackageClass.getPackage().getName());
    }
    // 如果都没有提取到,则提取默认的,即注解所标注的类所在包,也就是主启动类所在包
    if (packageNames.isEmpty()) {
        packageNames.add(ClassUtils.getPackageName(metadata.getClassName()));
    }
    this.packageNames = Collections.unmodifiableList(packageNames);
}

PackageImports的作用就是提取应用根包名,体现了约定大于配置。提取出根包路径后,调用外层的register方法。

(3)register方法
private static final String BEAN = AutoConfigurationPackages.class.getName();
public static void register(BeanDefinitionRegistry registry, String... packageNames) {
    // 检查IOC容器中是否有AutoConfigurationPackages这个Bean
    if (registry.containsBeanDefinition(BEAN)) {
        // 有这个Bean时,拿到构造方法,把根包路径packageNames作为参数传进去
        BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
        ConstructorArgumentValues constructorArguments =     beanDefinition.getConstructorArgumentValues();
        constructorArguments.addIndexedArgumentValue(0,     addBasePackages(constructorArguments, packageNames));
    }
    else {
        // 没有这个Bean时,则创建这个Bean并注册到IOC容器中,把根包路径packageNames作为构造方法的参数传进去
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(BasePackages.class);
        beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0,     packageNames);
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(BEAN, beanDefinition);
    }
}

由以上源码可知,这两个分支逻辑的共性在于:添加构造方法的参数。这个参数就是PackageImports提取出来的根包路径packageNames。

(4)BasePackages

那根包路径保存到哪里了?从else分支可以看到,实际上构造了一个BasePackages对象,内部维护了一个字符串数组以存放这些根包路径。

/**
 * Holder for the base package (name may be null to indicate no scanning).
 */
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;
    }
    // ...
}
(5)保存SpringBoot应用的根包路径作用

最后一个问题,保存SpringBoot应用的根包路径用来做什么?
SpringBoot可以方便地整合第三方技术。以MyBatis为例,当项目引入mybatis-spring-boot-starter依赖后,有一个MybatisAutoConfiguration类,其中有一个AutoConfiguredMapperScannerRegistrar组件。

public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {
    private BeanFactory beanFactory;

    public AutoConfiguredMapperScannerRegistrar() {
    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            // ...
            // 获取应用的根包路径
            List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
            // ...
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
            builder.addPropertyValue("processPropertyPlaceHolders", true);
            builder.addPropertyValue("annotationClass", Mapper.class);
            // 放置到组件构造器中
            builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(packages));
            // ...
            registry.registerBeanDefinition(MapperScannerConfigurer.class.getName(), builder.getBeanDefinition());
        }
    }

    // ...
}

由以上的源码可以,AutoConfiguredMapperScannerRegistrar是一个ImportBeanDefinitionRegistrar,用于向IOC容器注册MapperScannerConfigurer组件,用于Mapper接口扫描。在创建MapperScannerConfigurer组件时,应用的根包路径作为其中一个参数被设置进去,由此也就体现出basePackages的作用。

通过以上的分析,也就理解了SpringBoot的主启动类要在所有类的最外层。

2.5.3.3 AutoConfigurationImportSelector
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware