SpringBoot 源码分析(二)自动装配原理

本文基于 Spring Boot 3.4.x 源码编写,涉及部分 Spring Framework 6.2.x 源码,源码为开源项目 spring-projects/spring-boot 与 spring-projects/spring-framework(Apache 2.0 协议),文中引用均为学习目的的片段摘录,版权归原项目作者所有。

上一篇(一)run() 全景里我们讲到,SpringApplication.run() 的最后一步 refreshContext(context) 会调用容器的 refresh(),而 refresh 的第 5 步 invokeBeanFactoryPostProcessors 会触发 ConfigurationClassPostProcessor------配置类的解析、@ComponentScan 的扫描、自动装配,全部都发生在这一步。Spring 系列分析(二)讲配置类解析时我们留过一个尾巴:@EnableAutoConfiguration 看起来神秘,其实它就是一个 @Import(AutoConfigurationImportSelector.class)。本文就来把这个尾巴接上,把 Boot 最核心的机制------自动装配,讲透。

一、概述

先来点年代感。没有 SpringBoot 的 SSM 时代,配一个能跑的 Web 环境要写多少东西?web.xml 里注册 DispatcherServlet,Spring 配置里声明 InternalResourceViewResolver、DataSource、SqlSessionFactory、MapperScannerConfigurer、DataSourceTransactionManager......上十个 XML 标签或 JavaConfig 方法,一个都不能少,环境才能转起来。

而 SpringBoot 时代,加一个 spring-boot-starter-web 依赖、写一个 @SpringBootApplication 主类,Tomcat 起来了,MVC 通了,Jackson 能用了。这中间差出来的那部分 Bean 是谁注册进容器的?答案就是本文的主角------自动装配。

用一句话概括:自动装配就是 Boot 在启动时,按 classpath 的现状(你引了什么 starter、有什么类),把一批约定好的 Bean 批量注册进容器。它由三大件组成:

组成部分 位置 作用
@EnableAutoConfiguration spring-boot-autoconfigure 的注解 自动装配的入口,被 @SpringBootApplication 组合
AutoConfiguration.imports 清单 每个 jar 的 META-INF/spring/ 目录 登记了所有候选自动配置类的全限定名
条件注解 @ConditionalOnXxx spring-boot-autoconfigure 决定清单里的候选类"进不进"容器

用一张图标注出自动装配在整个启动链路中的位置(它挂在 Spring 系列讲过的 refresh 流程上):

本文的分析路线:先看入口与清单(三大件的前两件),再深入源码把"清单怎么被加载、条件怎么被评估"讲清楚,最后打开一个真实的自动配置类解剖,并用一个自定义 starter 的 demo 把全套机制验证一遍。

在进源码之前,先把一个容易混淆的边界划清楚:自动装配和组件扫描是两套并行的 Bean 来源,解决的是两个不同的问题 。@ComponentScan 扫的是"你自己写的类"------它以主类所在包为根,把标了 @Component/@Service/@Repository 的类注册进容器;自动装配处理的是"第三方 jar 里的类"------jar 包你根本扫不到(它们不在你的包路径下),Boot 用"清单 + 条件"这套机制替你决定引哪些。两者在 ConfigurationClassParser 里走的是同一条解析管线,只是入口不同:前者从 @ComponentScan 的 scan 动作进来,后者从 @Import(DeferredImportSelector) 进来。理解了这一点,"为什么 starter 里的类不需要扫描就能注入"就不再是魔法,而是清单登记 + 选择器导入的必然结果。

再把"清单登记"这个机制放进历史里看,它其实经历了三代演进,每一代都在解决上一代的痛点:

世代 机制 代表 痛点
一代 Java SPI META-INF/services/ + ServiceLoader 只能加载接口实现类,无条件过滤,加载即实例化
二代 spring.factories Spring Boot 1.x~2.x 键值对扁平结构,与测试切片、编译期校验配合差
三代 AutoConfiguration.imports Spring Boot 2.7 引入、3.x 独占 每个注解一份清单,可配合元数据预编译做启动优化

Java SPI 的局限最明显:ServiceLoader 加载的是"实现类"本身,谁来实例化、实例化后交给谁、依赖怎么注入,全都不管------它是类加载层面的插件机制,不是容器层面的装配机制。spring.factories 解决了"交给 Spring 容器"的问题,但一个文件里挤了几十种用途的键(EnableAutoConfiguration、EnvironmentPostProcessor、ApplicationContextInitializer......),自动配置只是其中一键,做编译期元数据提取和按注解拆分都很别扭。三代 .imports 文件把自动配置独立成"一个注解对应一份清单",文件名就是注解全限定名,于是 ImportCandidates.load(注解, classLoader) 这种通用加载模式成为可能------后面 2.3 节源码里会看到它,同一套机制还能被自定义注解复用。

还有一个容易被忽略的角度:自动装配本质上是一笔启动性能与开发效率的交换 。Spring 容器的启动成本与 BeanDefinition 数量近似成正比------每个配置类要解析、每个 Bean 要注册,后台还有 Bean 后置处理器扫过每一张定义表。没有自动装配时,一个中型 Web 项目可能只有一两百个 BeanDefinition;引齐 starter 之后,这份清单轻轻松松膨胀到四五百个。Boot 官方对这笔账的态度是"默认全配、给足开关":spring.boot.enableautoconfiguration=false 可以整体关闭(本文 2.3 节源码第一步就是它);@SpringBootApplication(exclude = ...) 可以按类排除;3.x 的清单预编译元数据(2.3 节末尾会讲)把候选过滤的成本压到查表级别;再往下还有懒加载(spring.main.lazy-initialization=true,把 Bean 实例化推迟到首次使用)和 AOT 这两道更重的闸门。理解了"装配数量 ↔ 启动耗时"这条曲线,你在做启动优化时才知道每一层开关各自省的是哪一段成本------这块会在(七)Bean 加载全链路串讲里用数据展开。

二、入口与清单

2.1 @EnableAutoConfiguration:一个注解,两层 import

先补一个绝大多数人天天见却未必拆过的前置知识。日常写在主类上的 @SpringBootApplication 其实是个"三合一"组合注解:@SpringBootConfiguration(本质是 @Configuration,标识主类是配置类,解析入口由它触发)、@ComponentScan(不带参数,默认扫描主类所在包及子包)、@EnableAutoConfiguration(本文主角)。三个注解各管一条装配来源:主类自身是配置类(@Bean 方法)、扫描拿到你的业务 Bean、自动配置补齐第三方组件------一条主类注解同时喂饱了配置类解析管线的三个入口 ,这就是它"一个注解顶一个工程样板"的全部原理。顺带一个推论:@SpringBootConfiguration 没有 @Inherited 之外的扫描语义,它必须和 @ComponentScan 在同一个类上(或同包),所以主类挪包 = 扫描范围挪包,业务代码搬出主包子树后"Bean 突然找不到"的事故源头在这里。

再回到入口注解的定义,spring-boot-autoconfigure 模块的 org.springframework.boot.autoconfigure.EnableAutoConfiguration:

java 复制代码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

	/**
	 * Environment property that can be used to override when auto-configuration is
	 * enabled.
	 */
	String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * @return the class names to exclude
	 * @since 1.3.0
	 */
	String[] excludeName() default {};

}

印证了 Spring 系列(二)里说的:@EnableAutoConfiguration 的本体就是一个 @Import(AutoConfigurationImportSelector.class) ,外加两个属性:exclude / excludeName(手动排除某些自动配置类)。ENABLED_OVERRIDE_PROPERTY 对应 spring.boot.enableautoconfiguration 配置项,设为 false 可以整体关掉自动装配,后面源码里会看到它的用处。

注解上还叠加了一层 @AutoConfigurationPackage,它的定义在同一个包下:

java 复制代码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

	/**
	 * Base packages that should be registered with {@link AutoConfigurationPackages}.
	 * <p>
	 * Use {@link #basePackageClasses} for a type-safe alternative to String-based package
	 * names.
	 * @return the back package names
	 * @since 2.3.0
	 */
	String[] basePackages() default {};

	/**
	 * Type-safe alternative to {@link #basePackages} for specifying the packages to be
	 * registered with {@link AutoConfigurationPackages}.
	 * ...
	 */
	Class<?>[] basePackageClasses() default {};

}

又是一层 @Import,这次导入的是一个 ImportBeanDefinitionRegistrar------AutoConfigurationPackages.Registrar,它的核心逻辑在 AutoConfigurationPackages 里:

java 复制代码
	/**
	 * {@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));
		}

	}

逻辑一句话:把标了 @EnableAutoConfiguration 的类(通常就是我们的主类)所在的包,注册成一个名为 org.springframework.boot.autoconfigure.AutoConfigurationPackages 的 BeanDefinition 存进容器 。这个"自动装配包路径"是给后面的组件用的------最典型的就是 JPA:@Entity 的扫描范围就取自这里,这也解释了 @SpringBootApplication 为什么必须放在根包下。

所以一个 @EnableAutoConfiguration 干了两件事:Registrar 登记"自动装配的基准包",AutoConfigurationImportSelector 负责真正的自动配置类导入。后者是本文的重头戏。

2.2 AutoConfiguration.imports:自动配置的清单文件

AutoConfigurationImportSelector 是怎么知道全世界有哪些自动配置类的?靠的是每个 jar 自带的一份清单文件。spring-boot-autoconfigure 自己的清单长这样(META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports,文件里每行一个全限定类名,此处摘录开头部分):

text 复制代码
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration
// ...(略,共 153 个)

值得注意的历史:2.7 之前这些类名登记在 META-INF/spring.factories 的 org.springframework.boot.autoconfigure.EnableAutoConfiguration 键下,2.7 起迁移到这份 .imports 文件(两处并存过渡),3.x 起只认 .imports 文件------所以网上那些"去 spring.factories 里找自动配置列表"的老教程,读 3.x 源码时会对不上号。

顺带把一个常见误解澄清掉:迁移的只是"自动配置"这一类条目,spring.factories 文件本身在 3.x 并没有消失 。SpringFactoriesLoader 依然在为其他扩展点服务------EnvironmentPostProcessor、ApplicationContextInitializer、AutoConfigurationImportListener、FailureAnalyzer、ApplicationListener 这些 SPI 条目还是登记在 META-INF/spring.factories 里,解析它们的代码走的是另一条加载路径(后续讲配置加载与监听器机制的文章会各自碰到)。所以准确的说法是:"自动配置清单从 spring.factories 里搬了出去",而不是"spring.factories 被废弃了"。自己写 starter 时也要按新约定把配置类登记进 .imports 文件,写错位置(比如还往 spring.factories 的老键里塞)在 3.x 下是不生效的,而且不会有任何报错------清单扫描根本不会看那个键,这是自定义 starter"写了但不生效"的高频原因之一。

清单是静态的、全量的:不管你的项目用了哪些依赖,这份文件都在那儿。真正"按需"的筛选发生在两道关卡上:第一道是 AutoConfigurationImportSelector 里的过滤,第二道是每个自动配置类上的条件注解。这两道关卡正是 2.3 节和 3.2 节的内容。

2.3 getAutoConfigurationEntry:候选类的筛选流水线

接下来进入 AutoConfigurationImportSelector。类声明先看一眼:

java 复制代码
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
		ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

	static final int ORDER = Ordered.LOWEST_PRECEDENCE - 1;
	// ...

两个信息:实现了 DeferredImportSelector (延后导入选择器,3.1 节专门讲它为什么重要),以及一堆 Aware 接口(启动早期由解析器手动注入 ClassLoader、BeanFactory、Environment 等依赖)。核心方法 getAutoConfigurationEntry 全文如下:

java 复制代码
	/**
	 * Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
	 * of the importing {@link Configuration @Configuration} class.
	 * @param annotationMetadata the annotation metadata of the configuration class
	 * @return the auto-configurations that should be imported
	 */
	protected AutoConfigurationEntry getAutoConfigurationEntry(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 = getConfigurationClassFilter().filter(configurations);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return new AutoConfigurationEntry(configurations, exclusions);
	}

这就是自动装配的主干流水线,六步走完,153 个候选只剩真正适用的那几十个。数字展开更直观:一个典型的 spring-boot-starter-web 项目,153 个候选经过第一道过滤器(classpath 元数据预筛)大约会剔掉近一半------ Cassandra、RabbitMQ、Batch 这些没引依赖的直接出局;幸存的几十个进入解析阶段,再被类上的 @ConditionalOnWebApplication、@ConditionalOnProperty、@ConditionalOnMissingBean 逐个裁决,最终 Positive matches 一般只有四五十个。也就是说,你每次启动享受的"开箱即用",是这条流水线在两百多个候选里现场筛出来的"四五十个恰好适用"------"按 classpath 现状装配"这句话,说的就是这组数字的关系:

  1. isEnabled :检查 spring.boot.enableautoconfiguration 配置,可以整体关掉自动装配;
  2. getAttributes :从主类的注解元数据里读出 exclude / excludeName 属性;
  3. getCandidateConfigurations:读清单文件,拿到全量候选类名;
  4. removeDuplicates + removeAll(exclusions):去重、剔除手动排除的类;
  5. getConfigurationClassFilter().filter(configurations) :第一道条件关卡,按 @ConditionalOnClass 等元数据批量预过滤(3.2 节细讲);
  6. fireAutoConfigurationImportEvents :发布 AutoConfigurationImportEvent,供监听器拿到"最终入选/被排除"的名单。

逐步展开看。第三步 getCandidateConfigurations 就是读清单的地方:

java 复制代码
	protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		ImportCandidates importCandidates = ImportCandidates.load(this.autoConfigurationAnnotation,
				getBeanClassLoader());
		List<String> configurations = importCandidates.getCandidates();
		Assert.notEmpty(configurations,
				"No auto configuration classes found in " + "META-INF/spring/"
						+ this.autoConfigurationAnnotation.getName() + ".imports. If you "
						+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

ImportCandidates.load 干的活:去 classpath 上扫描所有 jar 中 META-INF/spring/<注解全限定名>.imports 这个路径的文件(通过 ClassLoader.getResources),把行内容汇总成列表。错误信息也很有辨识度------如果你打包姿势不对导致清单丢了,启动时就会看到这个 No auto configuration classes found in META-INF/spring/...imports。

再看第四步的排除逻辑,getExclusions 汇总了三个来源:

java 复制代码
	protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		Set<String> excluded = new LinkedHashSet<>();
		excluded.addAll(asList(attributes, "exclude"));
		excluded.addAll(asList(attributes, "excludeName"));
		excluded.addAll(getExcludeAutoConfigurationsProperty());
		return getAutoConfigurationReplacements().replaceAll(excluded);
	}

注解的 exclude 属性、excludeName 属性、spring.autoconfigure.exclude 配置项,三个来源合一。removeDuplicates 的实现顺带看一眼,就是 LinkedHashSet 保序去重:

java 复制代码
	protected final <T> List<T> removeDuplicates(List<T> list) {
		return new ArrayList<>(new LinkedHashSet<>(list));
	}

第五步的 ConfigurationClassFilter 是第一道条件关卡------它不解析配置类,只拿着类名 + 预先生成的元数据做批量过滤:

java 复制代码
	private static class ConfigurationClassFilter {

		private final AutoConfigurationMetadata autoConfigurationMetadata;

		private final List<AutoConfigurationImportFilter> filters;

		ConfigurationClassFilter(ClassLoader classLoader, List<AutoConfigurationImportFilter> filters) {
			this.autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(classLoader);
			this.filters = filters;
		}

		List<String> filter(List<String> configurations) {
			long startTime = System.nanoTime();
			String[] candidates = StringUtils.toStringArray(configurations);
			boolean skipped = false;
			for (AutoConfigurationImportFilter filter : this.filters) {
				boolean[] match = filter.match(candidates, this.autoConfigurationMetadata);
				for (int i = 0; i < match.length; i++) {
					if (!match[i]) {
						candidates[i] = null;
						skipped = true;
					}
				}
			}
			// ...(略,trace 日志与结果收集)
			return result;
		}

	}

AutoConfigurationImportFilter 的默认实现正是 OnClassCondition、OnBeanCondition 这些条件类的"另一重身份"(注意 OnClassCondition 的 javadoc:"{@link Condition} and {@link AutoConfigurationImportFilter} that checks for the presence or absence of specific classes" )。这里用 match(String[], AutoConfigurationMetadata) 批量打分,autoConfigurationMetadata 是启动时从 spring-autoconfigure-metadata.properties 读进来的预编译元数据(类名 → 该类用了哪些条件注解),不用加载配置类字节码就能提前筛掉一批,这是 Boot 的启动性能优化之一。

这份元数据文件值得单独说两句,因为它是"读源码读不到"的部分------它不在源码仓库里,而是编译期生成的 。spring-boot-autoconfigure 构建时由注解处理器扫描每个自动配置类的 @Conditional* 注解,把"哪个类用了哪些条件、参数是什么"汇总成一个 properties 文件打进 jar,形如:

properties 复制代码
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.ConditionalOnClass=javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annotation.WebMvcConfigurer
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.ConditionalOnWebApplication=SERVLET

启动时 AutoConfigurationMetadataLoader.loadMetadata(classLoader) 一次性读进内存,过滤器对每个候选类名做一个 properties.get(类名 + ".ConditionalOnClass") 级别的查表------如果没有这份元数据,预过滤就得加载每个候选类的字节码自己解析注解,153 个类的解析成本会实打实压在启动路径上。自定义 starter 想享受同样的优化,要在自己的构建里挂上 spring-boot-configuration-processor(配合 @AutoConfiguration 的编译处理),否则你的配置类进不了元数据文件------不会影响正确性(还有 3.2 节的常规条件评估兜底),但会退化为"每次启动都要加载字节码才能筛"。

用一张类图整理一下本章出现的角色体系:

流水线讲完了,但有一个悬而未决的问题:getAutoConfigurationEntry 是 DeferredImportSelector#selectImports 的内部方法,它到底在什么时机被调用?为什么 Boot 要选 DeferredImportSelector 这个接口? 这是理解自动装配的关键,下一节深入。

三、源码解析过程

3.1 deferred 机制:自动配置为什么"最后处理"

回顾 Spring 系列(二)配置类解析:ConfigurationClassPostProcessor 在 invokeBeanFactoryPostProcessors 阶段被触发,它内部委托 ConfigurationClassParser 递归解析每一个配置类,遇到 @Import 注解时走 processImports()。我们直接看这段源码(spring-context 6.2.x,ConfigurationClassParser):

java 复制代码
	private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
			Collection<SourceClass> importCandidates, Predicate<String> filter, boolean checkForCircularImports) {

		if (importCandidates.isEmpty()) {
			return;
		}

		if (checkForCircularImports && isChainedImportOnStack(configClass)) {
			this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
		}
		else {
			this.importStack.push(configClass);
			try {
				for (SourceClass candidate : importCandidates) {
					if (candidate.isAssignable(ImportSelector.class)) {
						// Candidate class is an ImportSelector -> delegate to it to determine imports
						// 候选类是 ImportSelector,委托它决定要导入哪些类
						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) {
							filter = filter.or(selectorFilter);
						}
						// 关键分支:DeferredImportSelector 不立即处理,先"挂号"
						if (selector instanceof DeferredImportSelector deferredImportSelector) {
							this.deferredImportSelectorHandler.handle(configClass, deferredImportSelector);
						}
						else {
							// 普通 ImportSelector 立即执行,返回的类继续递归 processImports
							String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
							Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, filter);
							processImports(configClass, currentSourceClass, importSourceClasses, filter, false);
						}
					}
					else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
						// Candidate class is an ImportBeanDefinitionRegistrar ->
						// delegate to it to register additional bean definitions
						// Registrar 先暂存到配置类对象上,等 BeanDefinition 注册阶段再回调
						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), filter);
					}
				}
			}
			// ...(略,异常处理与 importStack.pop())
		}
	}

重点就在中间那个分支:Spring 把 @Import 的候选分成了三类,其中 ImportSelector 又按是否实现 DeferredImportSelector 分成"立即处理"和"延后处理"两批 。AutoConfigurationImportSelector 实现了 DeferredImportSelector,所以它在解析主类时只是被"挂号"进 handler,并不马上干活。

"挂号"和"办理"都在 DeferredImportSelectorHandler 里(同文件内部类):

java 复制代码
	private class DeferredImportSelectorHandler {

		@Nullable
		private List<DeferredImportSelectorHolder> deferredImportSelectors = new ArrayList<>();

		/**
		 * Handle the specified {@link DeferredImportSelector}. If deferred import
		 * selectors are being collected, this registers this instance to the list. If
		 * they are being processed, the {@link DeferredImportSelector} is also processed
		 * immediately according to its {@link DeferredImportSelector.Group}.
		 * @param configClass the source configuration class
		 * @param importSelector the selector to handle
		 */
		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);
			}
		}

		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<>();
			}
		}
	}

handle() 只往列表里加 holder;真正执行的是 process()。那 process() 谁来调?在 ConfigurationClassParser#process() 的最后------也就是主类等所有"入口配置类"的递归解析(@ComponentScan 扫描、@Import 递归、@Bean 方法收集)全部完成之后,才走到这一行:

java 复制代码
		this.deferredImportSelectorHandler.process();

时序梳理一下(对应前面 3.1 的三段源码):

  1. 解析主类 → 发现 @Import(AutoConfigurationImportSelector.class) → handle() 挂号,先继续 解析 @ComponentScan、@Bean 方法等用户配置;
  2. 主类这一层解析完毕,process() 尾声统一办理挂号的 deferred 选择器;
  3. processGroupImports() 按 Group 归组执行------AutoConfigurationImportSelector 通过 getImportGroup() 指定了自己的分组:
java 复制代码
	@Override
	public Class<? extends Group> getImportGroup() {
		return AutoConfigurationGroup.class;
	}

分组机制的意义:同一个 Group 的多次 process() 收集到的结果可以合并排序后统一返回 ,而不是每来一个选择器就立即处理一批。看 DeferredImportSelectorGroupingHandler 与 DeferredImportSelectorGrouping 的协作:

java 复制代码
		@SuppressWarnings("NullAway")
		void processGroupImports() {
			for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
				Predicate<String> filter = grouping.getCandidateFilter();
				grouping.getImports().forEach(entry -> {
					ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata());
					try {
						processImports(configurationClass, asSourceClass(configurationClass, filter),
								Collections.singleton(asSourceClass(entry.getImportClassName(), filter)),
								filter, false);
					}
					// ...(略,异常包装)
				});
			}
		}
java 复制代码
		/**
		 * Return the imports defined by the group.
		 * @return each import with its associated configuration class
		 */
		Iterable<Group.Entry> getImports() {
			for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
				this.group.process(deferredImport.getConfigurationClass().getMetadata(),
						deferredImport.getImportSelector());
			}
			return this.group.selectImports();
		}

getImports() 里先回调每个 holder 的 group.process(...)(收集阶段),再调用 group.selectImports()(产出阶段)。AutoConfigurationGroup 的 process() 里调用的正是 2.3 ��那条 getAutoConfigurationEntry() 流水线,然后把结果存起来;selectImports() 负责排序输出:

java 复制代码
		@Override
		public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
			Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
					() -> String.format("Only %s implementations are supported, got %s",
							AutoConfigurationImportSelector.class.getSimpleName(),
							deferredImportSelector.getClass().getName()));
			// ...(略,replacements 一致性校验)
			AutoConfigurationEntry autoConfigurationEntry = autoConfigurationImportSelector
				.getAutoConfigurationEntry(annotationMetadata);
			this.autoConfigurationEntries.add(autoConfigurationEntry);
			for (String importClassName : autoConfigurationEntry.getConfigurations()) {
				this.entries.putIfAbsent(importClassName, annotationMetadata);
			}
		}

		@Override
		public Iterable<Entry> selectImports() {
			if (this.autoConfigurationEntries.isEmpty()) {
				return Collections.emptyList();
			}
			// ...(略,合并 exclusions 并从结果中剔除)
			processedConfigurations.removeAll(allExclusions);
			return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream()
				.map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
				.toList();
		}

sortAutoConfigurations 用 AutoConfigurationSorter 按 @AutoConfigureOrder、@AutoConfigureBefore、@AutoConfigureAfter 排出优先顺序------这就是为什么 DispatcherServletAutoConfiguration 总是排在 WebMvcAutoConfiguration 前面(后者类上写着 @AutoConfiguration(after = { DispatcherServletAutoConfiguration.class, ... }))。

这一节是自动装配的"设计动机"所在 :DeferredImportSelector 延后机制保证了:

  • 用户的 @Bean、@ComponentScan、@Import 先解析、先注册 BeanDefinition;
  • 自动配置类最后才批量进场;
  • 于是 3.2 节的 @ConditionalOnMissingBean 评估时,看到的是"全量用户 Bean"------"用户配置优先,Boot 兜底让位"的根因就在这里。如果没有 deferred,Boot 的兜底 Bean 反而会先注册,用户的同名 Bean 就会出现冲突或被忽略。

关于"延后"还有三个工程细节值得点出来,它们是读 3.x 源码时容易卡住的点。

第一,selectImports() 返回的是类名字符串数组 而不是 Class 对象,这不是偷懒:整个解析阶段 Spring 都在用 ASM 读字节码元数据(Spring 系列(二)讲过),类没有被 JVM 真正加载,如果这里返回 Class 就会触发加载,@ConditionalOnClass "引用不存在的类也不报错"的前提就被破坏了。类名一路传递到 processImports(),最终由 processGroupImports() 把幸存的自动配置类当普通配置类递归解析------此时才会真正加载类字节码走条件评估。字符串在前、Class 在后,这是贯穿整套机制的一条主线。

第二,排序发生在字符串层面 而不是类层面。sortAutoConfigurations 拿着 AutoConfigurationSorter 对类名列表排序:先按 @AutoConfigureOrder 的值,再用 @AutoConfigureBefore/@AutoConfigureAfter 声明的关系做拓扑调整,最后按字母序兜底。注意顺序声明写在被排序者自己的注解上 (WebMvcAutoConfiguration 自己声明 after = DispatcherServletAutoConfiguration.class),每个 jar 只管声明自己相对别人的位置,不需要知道全貌------分布式系统里常见的"去中心化排序约定"。

第三,3.4 起 getAutoConfigurationReplacements() 还引入了改名替换 机制:自动配置类在官方内部重构改名后,通过一个映射文件把老类名映射到新类名,用户配置里写了老类名的 exclude 依然有效。这是一个纯粹的兼容性工程细节,但读到 getExclusions 末尾那行 replaceAll(excluded) 时应该知道它在干什么------不是"排除的替换",而是"名单的改名"。

deferred 时序还给你留了一个运行期实证 的窗口:AutoConfigurationImportEvent(流水线第 6 步 fireAutoConfigurationImportEvents 发布)带着"最终入选 + 被排除"两份名单,注册一个 AutoConfigurationImportListener(登记在 spring.factories 里,2.2 节说过它还在)就能在启动日志里把两条名单打出来。更省事的做法是利用 --debug 的报告交叉验证时序------报告里 Negative matches 有一个配置类 A,而某个 @ConditionalOnMissingBean 的判断恰好依赖 A 注册的 Bean,把报告上下文对照起来读,你能直观看到"用户 Bean 全部注册完毕"与"自动配置评估"两个动作的先后关系。源码读到这里,时序就不再是从代码里"推断"出来的结论,而是每次启动都能复现的事实。

3.2 条件注解评估:classpath 与容器两道探测

自动配置类进场之前还有第二道、也是更精细的一道关卡:条件注解 。先看最常用的 ConditionalOnClass 定义(spring-boot-autoconfigure,org.springframework.boot.autoconfigure.condition 包):

java 复制代码
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnClassCondition.class)
public @interface ConditionalOnClass {

	/**
	 * The classes that must be present. Since this annotation is parsed by loading class
	 * bytecode, it is safe to specify classes here that may ultimately not be on the
	 * classpath, only if this annotation is directly on the affected component and
	 * <b>not</b> if this annotation is used as a composed, meta-annotation. In order to
	 * use this annotation as a meta-annotation, only use the {@link #name} attribute.
	 * @return the classes that must be present
	 */
	Class<?>[] value() default {};

	/**
	 * The classes names that must be present.
	 * @return the class names that must be present.
	 */
	String[] name() default {};

}

它就是 Spring 原生 @Conditional(OnClassCondition.class) 的特化。条件评估的引擎是 Spring 系列(三)提过的 ConditionEvaluator:解析配置类时(PARSE_CONFIGURATION 阶段)与注册 @Bean 方法前(REGISTER_BEAN 阶段)各有一次回调,最终落到每个 Condition 的 getMatchOutcome()。

OnClassCondition.getMatchOutcome 的关键段:

java 复制代码
	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		ClassLoader classLoader = context.getClassLoader();
		ConditionMessage matchMessage = ConditionMessage.empty();
		List<String> onClasses = getCandidates(metadata, ConditionalOnClass.class);
		if (onClasses != null) {
			List<String> missing = filter(onClasses, ClassNameFilter.MISSING, classLoader);
			if (!missing.isEmpty()) {
				return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnClass.class)
					.didNotFind("required class", "required classes")
					.items(Style.QUOTE, missing));
			}
			matchMessage = matchMessage.andCondition(ConditionalOnClass.class)
				.found("required class", "required classes")
				.items(Style.QUOTE, filter(onClasses, ClassNameFilter.PRESENT, classLoader));
		}
		List<String> onMissingClasses = getCandidates(metadata, ConditionalOnMissingClass.class);
		if (onMissingClasses != null) {
			List<String> present = filter(onMissingClasses, ClassNameFilter.PRESENT, classLoader);
			if (!present.isEmpty()) {
				return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingClass.class)
					.found("unwanted class", "unwanted classes")
					.items(Style.QUOTE, present));
			}
			// ...(略,@ConditionalOnMissingClass 的匹配分支)
		}
		return ConditionOutcome.match(matchMessage);
	}

逻辑直白:取出注解里要���的类名列表,用 ClassNameFilter.MISSING 找出 classpath 上缺失的,缺了任何一个就返回 noMatch(不匹配原因写进 ConditionMessage)。注意这里的类名从 metadata 上读出来的是字符串 (Spring 系列(二)讲过:配置类用 ASM 读字节码解析,类根本没被 JVM 加载),探测靠 ClassLoader.forName / getResource,所以 @ConditionalOnClass 里引用不存在的类也不会 NoClassDefFoundError------这就是它能让"同一个配置类适配有无依赖两种 classpath"的原因。

OnBeanCondition 则是另一族,管的是容器里有没有某个 Bean 。先注意它的 getConfigurationPhase():

java 复制代码
class OnBeanCondition extends FilteringSpringBootCondition implements ConfigurationCondition {

	@Override
	public ConfigurationPhase getConfigurationPhase() {
		return ConfigurationPhase.REGISTER_BEAN;
	}

REGISTER_BEAN 阶段意味着这类条件在注册 BeanDefinition 时才评估 (而不是解析配置类时),这样才能看到容器里已注册的 Bean。getMatchOutcome 按注解类型依次评估,核心的 @ConditionalOnMissingBean 分支:

java 复制代码
	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		ConditionOutcome matchOutcome = ConditionOutcome.match();
		MergedAnnotations annotations = metadata.getAnnotations();
		if (annotations.isPresent(ConditionalOnBean.class)) {
			Spec<ConditionalOnBean> spec = new Spec<>(context, metadata, annotations, ConditionalOnBean.class);
			matchOutcome = evaluateConditionalOnBean(spec, matchOutcome.getConditionMessage());
			if (!matchOutcome.isMatch()) {
				return matchOutcome;
			}
		}
		// ...(略,ConditionalOnSingleCandidate 分支)
		if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
			Spec<ConditionalOnMissingBean> spec = new Spec<>(context, metadata, annotations,
					ConditionalOnMissingBean.class);
			matchOutcome = evaluateConditionalOnMissingBean(spec, matchOutcome.getConditionMessage());
			if (!matchOutcome.isMatch()) {
				return matchOutcome;
			}
		}
		return matchOutcome;
	}
java 复制代码
	private ConditionOutcome evaluateConditionalOnMissingBean(Spec<ConditionalOnMissingBean> spec,
			ConditionMessage matchMessage) {
		MatchResult matchResult = getMatchingBeans(spec);
		if (matchResult.isAnyMatched()) {
			String reason = createOnMissingBeanNoMatchReason(matchResult);
			return ConditionOutcome.noMatch(spec.message().because(reason));
		}
		return ConditionOutcome.match(spec.message(matchMessage).didNotFind("any beans").atAll());
	}

getMatchingBeans 拿着 beanFactory.getBeanNamesForType(...) 到容器里找:找到了任意一个匹配的 Bean,条件就不成立,Boot 的默认 Bean 让位 。还有一个容易忽略的约束,@ConditionalOnMissingBean 的 javadoc 里写得很清楚:

The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.

它只能看到"到目前为止已处理的 BeanDefinition",所以官方强烈建议只把它用在自动配置类上,且依赖 @AutoConfigureAfter 保证顺序。这也再次呼应 3.1 节:deferred 机制保证了自动配置处理时用户 Bean 已经全量注册完毕。

另外两个日常高频的条件类,把探测原理点到为止。OnPropertyCondition(@ConditionalOnProperty 的引擎)的判断路径:把注解的 prefix + name 拼成属性名,逐个查 Environment 的属性源(宽松绑定由属性名规范化保证,greeter.enabled 与 greeter-enabled 等价);查到了就与 havingValue 做字符串比较,没查到则看 matchIfMissing------false 时直接判不匹配。它不经过 Binder 的类型转换体系,是纯字符串层面的协议,所以 havingValue 里写 "True" 而配置是 true 会失配(3.2 全家桶表里的坑就是从这来的)。OnWebApplicationCondition 则分两步探测:先看 Environment 是不是 ConfigurableWebEnvironment(标准 Web 启动的标志),SERVLET 类型再确认 classpath 上有 DispatcherServlet 相关类、REACTIVE 类型确认有 WebHandler------所以"引了 spring-web 依赖但 main 方法就是普通应用"不会误判成 Web 环境,判断依据是启动形态而不只是依赖。

最后,所有条件评估的结果都会被 ConditionEvaluationReport 记录下来(哪个配置类、哪个条件、匹配与否、原因),启动失败时这个报告会直接打进控制台;平时加 --debug 启动(或在配置里写 debug: true),就能看到著名的 CONDITIONS EVALUATION REPORT------" Positive matches"(生效)与"Exclusions"/"Negative matches"(未生效及原因)。排查"我的自动配置为什么没生效",看它比看博客快。

全家桶之外再留一个进阶出口:条件注解体系是完全开放的,任何实现了 org.springframework.context.annotation.Condition 的类都能作为装配开关。Condition 接口只有一个方法:

java 复制代码
public interface Condition {

	/**
	 * Determine if the condition matches.
	 * @param context the condition context
	 * @param metadata the metadata of the {@link Configuration @Configuration} class
	 * or {@link Bean @Bean} method being checked
	 * @return {@code true} if the condition matches and the component can be registered,
	 * or {@code false} to veto the annotated component's registration
	 */
	boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}

ConditionContext 把决策需要的四样东西全部给到:ClassLoader(classpath 探测)、Environment(读配置)、BeanFactory(查已有 Bean)、Registry(查 BeanDefinition)。所以 OnClass、OnProperty、OnBean 三族条件的全部能力,你都可以基于这一个方法自己组合出来------内部中间件团队做"灰度开关式装配"(比如按环境变量决定某套 Bean 是否注册)就是这么玩的。自己写时注意两点:实现类要放在能被扫到的地方并通过 @Conditional(MyCondition.class) 引用;Boot 的 @ConditionalOnXxx 都继承 FilteringSpringBootCondition 以同时充当批量过滤器,自定义条件只参与单类评估、不进 2.3 节的元数据预筛------不影响正确性,但性能敏感的超大项目里要注意这点差异。

读到这里值得停一下,把 Boot 提供的条件注解全家桶摆到一张表里系统过一遍。日常开发里大多数人只用过前三个,但排 starter 的疑难杂症时,后面几个往往才是钥匙:

注解 语义 评估阶段 高频坑
@ConditionalOnClass classpath 上存在指定类 PARSE_CONFIGURATION 组合注解(元注解)场景必须用 name 属性写类名字符串,直接写 .class 会提前触发加载
@ConditionalOnMissingClass classpath 上缺失指定类 PARSE_CONFIGURATION 只支持 name 字符串(不允许写 .class------都缺了还怎么加载)
@ConditionalOnBean 容器存在指定类型 Bean REGISTER_BEAN 看到的只是"评估时刻已注册"的 Bean,非自动配置场景慎用
@ConditionalOnMissingBean 容器缺失指定类型 Bean REGISTER_BEAN 不带参数默认按方法返回类型匹配;顺序敏感,必须配 @AutoConfigureAfter
@ConditionalOnSingleCandidate 容器存在唯一(或主)候选 Bean REGISTER_BEAN 有多个实现但没标 @Primary 时不匹配
@ConditionalOnProperty 配置项存在/等于期望值 PARSE_CONFIGURATION 属性名走宽松绑定(kebab-case);matchIfMissing 默认 false,"不配置即关闭"
@ConditionalOnWebApplication 是 Web 应用(可指定 SERVLET/REACTIVE) PARSE_CONFIGURATION 引入了 spring-web 但非 Web 启动时不匹配,常见于工具模块误引 starter
@ConditionalOnResource classpath 存在指定资源文件 PARSE_CONFIGURATION 路径要带协议前缀写法(如 classpath:/META-INF/xxx)
@ConditionalOnJava JVM 版本范围 PARSE_CONFIGURATION 只认版本号区间,用 -Djava.version 模拟,别真换 JDK 试
@ConditionalOnExpression SpEL 表达式为 true PARSE_CONFIGURATION 依赖 Environment 就绪,启动极早期(如 EnvironmentPostProcessor 里)不可用

两个细节展开说。其一是 @ConditionalOnProperty 的宽松绑定:prefix = "greeter" + name = "enabled" 对应的配置写 greeter.enabled、greeter-enabled、GREETER_ENABLED(环境变量)都能命中,这是 Binder 的属性源规范化在起作用(配置加载机制是(四)的主题,这里先留个钩子)。但反过来的坑很常见------havingValue = "True" 与配置值 true 是字符串精确比较,大小写不宽松,写了非期望值直接不匹配,而默认 matchIfMissing = false 意味着没配置也不匹配,于是"以为加个开关默认开启,实际忘了配所以没开"。

其二是两阶段的评估时机差异 ,这是条件注解几乎所有"玄学失效"的根源。classpath 类条件(OnClass、OnProperty、OnWebApplication)在配置类解析阶段(PARSE_CONFIGURATION)评估,此时只看字节码和环境,结论稳定;Bean 类条件(OnBean、OnMissingBean、OnSingleCandidate)推迟到注册阶段(REGISTER_BEAN)评估,看到的容器内容取决于配置类的处理顺序 。同一个 @ConditionalOnMissingBean,写在自动配置类里和写在你自己的 @Configuration 里,看到的"世界"完全不同:自动配置类被 deferred 到最后处理,看到的是全量用户 Bean;而你的 @Configuration 若按字母序排在别的配置类前面处理,后面的类里注册的 Bean 它一无所知。官方 javadoc 里那句"strongly recommended to use this condition on auto-configuration classes only"不是风格建议,是时序正确性的硬约束。

再把这笔性能账算清楚。153 个候选类的条件评估,粗算下来要执行几百次 classpath 探测(每次 Class.forName / getResource 都是 I/O)和几十次容器查表,串行跑下来在传统硬盘或容器冷启动场景里能占到启动耗时的可感比例。Boot 给的三层减负在代码里都能对上号:.imports 清单本身是纯文本(比 2.7 前解析整个 spring.factories 更轻);spring-autoconfigure-metadata.properties 预编译元数据把最贵的"加载字节码解析注解"提前到编译期(2.3 节已展开);过滤器 match() 返回 boolean[] 批量打分,一次循环处理全部候选,避免逐类回调。你在 --debug 报告里看到的每个 Negative match,背后都是这条被优化过的路径在毫秒级完成的判断------机制的正确性与启动性能,在 Boot 里是同一个设计的两面。

3.3 打开一个真实自动配置:WebMvcAutoConfiguration

机制讲完,打开 spring-boot-autoconfigure 里最贴近日常的一个真实自动配置类------WebMvcAutoConfiguration。类头注解:

java 复制代码
@AutoConfiguration(after = { DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@ImportRuntimeHints(WebResourcesRuntimeHints.class)
public class WebMvcAutoConfiguration {

五个注解层层设卡,正好是前面所有机制的实战演示:

  • @AutoConfiguration(after = ...):声明排序,排在 DispatcherServlet 相关配置之后(AutoConfigurationSorter 消费它);
  • @ConditionalOnWebApplication(type = Type.SERVLET):只在 Servlet Web 环境(非 Reactive)生效;
  • @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }):classpath 上有 spring-webmvc 才生效------没引 spring-boot-starter-web 时整个类直接跳过,这就是"按 classpath 现状装配"的最直接体现;
  • @ConditionalOnMissingBean(WebMvcConfigurationSupport.class):类级让位开关 ,只要容器里出现了 WebMvcConfigurationSupport 类型的 Bean,整个 WebMvcAutoConfiguration 放弃注册。

第四条是老面试题"加了 @EnableWebMvc 之后 Boot 的 MVC 默认配置为什么全没了"的答案:@EnableWebMvc 会导入 DelegatingWebMvcConfiguration,它继承自 WebMvcConfigurationSupport,于是类级 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) 不满足,Boot 这套配置整体让位,MVC 的所有组件全靠 WebMvcConfigurationSupport 那一套(这也是"全量接管"模式)。"全没掉"具体是没了什么?对照 Boot 默认清单就一目了然:静态资源映射(classpath:/static、/public 等五个位置与缓存策略)、ContentNegotiatingViewResolver 的聚合视图解析、默认的 HandlerMethodArgumentResolver 集合补齐、Jackson 消息转换器的默认配置与 ObjectMapper 定制钩子、路径匹配与 CORS 的默认策略、DispatcherServlet 的启动参数------这些统统来自 WebMvcAutoConfiguration 的内部配置,让位之后每一项都要自己重新声明。所以工程上对 @EnableWebMvc 的正确认知是:它不是"开启 MVC"(没它 MVC 也开着),而是"退掉 Boot 的默认装配、换全量自管模式",是个比 @Configuration 重得多的决定。

再往下看类里嵌套的内部配置,方法级条件注解的用法:

java 复制代码
	@Bean
	@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
	@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled")
	public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
		return new OrderedHiddenHttpMethodFilter();
	}

	// Defined as a nested config to ensure WebMvcConfigurer is not read when not
	// on the classpath
	// 定义为嵌套配置类:classpath 上没有 WebMvcConfigurer 时不会读这个类
	@Configuration(proxyBeanMethods = false)
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {

以及 WebMvcAutoConfigurationAdapter 里三个典型的"兜底 Bean":

java 复制代码
	@Bean
	@ConditionalOnMissingBean
	public InternalResourceViewResolver defaultViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix(this.mvcProperties.getView().getPrefix());
		resolver.setSuffix(this.mvcProperties.getView().getSuffix());
		return resolver;
	}

	@Bean
	@ConditionalOnBean(View.class)
	@ConditionalOnMissingBean
	public BeanNameViewResolver beanNameViewResolver() {
		BeanNameViewResolver resolver = new BeanNameViewResolver();
		resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
		return resolver;
	}

	@Bean
	@ConditionalOnBean(ViewResolver.class)
	@ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
	public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
		ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
		resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));
		// ContentNegotiatingViewResolver uses all the other view resolvers to locate
		// a view so it should have a high precedence
		// CNVR 负责聚合其他视图解析器的结果,所以优先级最高
		resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
		return resolver;
	}

@ConditionalOnMissingBean 不带参数时默认匹配 @Bean 方法的返回类型 (这是 ConditionalOnMissingBean javadoc 明确写的规则),所以 defaultViewResolver 的含义是:容器里没有 InternalResourceViewResolver 类型的 Bean 时,Boot 才注册这个默认的。你自己定义了一个视图解析器,Boot 的 defaultViewResolver 自动让位------不冲突、不覆盖。

最后回答那个衍生面试题:"我们自定义了 WebMvcConfigurer,为什么 Boot 的默认配置没被干掉,我们的扩展又生效了?" 因为让位的分水岭是 WebMvcConfigurationSupport(类级条件),而 WebMvcConfigurer 走的是另一条路:WebMvcAutoConfigurationAdapter 自己就实现了 WebMvcConfigurer,DelegatingWebMvcConfiguration 会把容器里所有 WebMvcConfigurer 类型的 Bean 收集起来逐个回调(addResourceHandlers、configureContentNegotiation 等)。Boot 的默认规则先注册,我们的 WebMvcConfigurer 只是"追加"在默认规则之上------两种机制一让位、一委托,这就是 Boot 兼容性与可扩展性并存的设计。

解剖这个类还有两个值得学走的工程模式。第一个是构造器参数注入 + ObjectProvider 兜底 :WebMvcAutoConfigurationAdapter 的依赖全部走构造器注入,且"可有可无"的依赖都用 ObjectProvider<Xxx>(或 ObjectProvider<Xxx[]>)接------比如消息转换器、视图解析器这类"用户可能自定义、可能没有"的组件。这是自动配置类的标准姿势:构造器注入保证依赖不可变,ObjectProvider.getIfAvailable() / stream() 保证缺失时不炸、存在时逐个消费,比字段 @Autowired(required=false) 干净得多。自己写 starter 时照抄这个模式,基本不会踩依赖时机问题。

第二个是 @Configuration(proxyBeanMethods = false) 的取舍。proxyBeanMethods = false 意味着容器不为这个配置类生成 CGLIB 代理 ,@Bean 方法之间的直接调用不会被拦截增强------两个 @Bean 方法 A() 里调 B() 时,拿到的不是容器里的单例 B,而是新建的第二个实例。好处是省掉了代理生成的开销(每个自动配置类都省一点,几百个类加起来对启动速度的贡献可观),代价是同配置类内 @Bean 方法互调语义失效 。Boot 官方自动配置几乎全部声明 proxyBeanMethods = false,并通过"把依赖声明成 @Bean 方法参数"来规避互调需求(参数走的是容器解析,天然单例)。这也是 @AutoConfiguration 注解的默认值------它内部组合的就是 @Configuration(proxyBeanMethods = false)。自己写配置类时判断标准很简单:没有方法间互调就关掉代理,白赚启动性能。

顺带补一条与自动配置密切相关的配置绑定链路:WebMvcAutoConfigurationAdapter 上挂着 @EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class }),这两个 XxxProperties 类(@ConfigurationProperties("spring.mvc") 等)负责把 spring.mvc.* 配置项绑定成强类型对象,再由 @Bean 方法注入使用------自动配置类的"可配置性"全部来自这条 Properties 链路 ,server.port、spring.mvc.view.prefix 之所以能改行为,是因为自动配置类消费的是 Properties 对象而不是写死的常量。这套"清单进候选 → 条件定生死 → Properties 定参数"的三层结构,就是 Boot 自动配置类的完整骨架。

同样的五注解套路还可以再看一个更精简的实例------DispatcherServletAutoConfiguration,它只有几十行,却把"类级设卡 + 内部嵌套配置 + 方法级让位"全部演示了一遍。类头两道卡:

java 复制代码
@AutoConfiguration(after = CodecsAutoConfiguration.class)
@ConditionalOnWebApplication(type = Type.SERVLET)
public class DispatcherServletAutoConfiguration {

	public static final String DEFAULT_DISPATCHER_SERVLET_BEAN_NAME = "dispatcherServlet";
	// ...

内部两个嵌套配置类各管一件事:DispatcherServletConfiguration 负责 dispatcherServlet 本体的注册,方法上挂着 @ConditionalOnClass(ServletRegistration.class) 和 @ConditionalOnMissingBean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)------按 Bean 名字让位 ,你自己定义了名叫 dispatcherServlet 的 Bean,Boot 的默认 Servlet 注册直接退场;另一个 DispatcherServletRegistrationConfiguration 负责把 Servlet 注册进内嵌容器(DispatcherServletRegistrationBean),同样挂 @ConditionalOnMissingBean(value = ..., name = ...),并且用 @ConditionalOnBean(type = ...) 声明"只有 dispatcherServlet 存在时才注册"------嵌套配置类之间也靠条件注解建立依赖顺序。这里能看出 Boot 内部配置的行文规律:类级条件管"这组配置整体是否相关",方法级条件管"单个 Bean 是否让位",名字条件管"用户同名自定义优先"。读任何 starter 源码,照这个套路扫一遍注解,十几个 Bean 的装配关系几分钟就能读出骨架。

3.4 自定义 starter 的原理对照

机制学完,用"造一个 starter"来对照验证。官方 starter 命名是 spring-boot-starter-xxx,第三方约定用 xxx-spring-boot-starter,通常拆两个模块:

模块 内容
xxx-spring-boot-autoconfigure 配置类、业务类、配置属性类,承载清单文件
xxx-spring-boot-starter 空壳聚合模块,只依赖 autoconfigure(可能再带上一组依赖)

最小骨架(完整可运行版在第四节 demo 里):

java 复制代码
// 业务类
public class GreeterService {

    private final String name;

    public GreeterService(String name) {
        this.name = name;
    }

    public String greet() {
        return "Hello, " + name + "!";
    }
}
java 复制代码
// 自动配置类:三件套一个不少
@AutoConfiguration
@ConditionalOnClass(GreeterService.class)
@EnableConfigurationProperties(GreeterProperties.class)
public class GreeterAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public GreeterService greeterService(GreeterProperties properties) {
        return new GreeterService(properties.getName());
    }
}

对照本文知识点,每个零件各就各位:

  • 清单文件 :autoconfigure 模块里放 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports,内容一行 com.example.greeter.autoconfigure.GreeterAutoConfiguration------2.2 节的 ImportCandidates.load 就是通过 classpath 扫描把所有 jar 的这份文件汇总起来的,所以你的 starter 只要被依赖,配置类就自动进入候选名单;
  • @ConditionalOnClass:3.2 节的 classpath 探测,业务类不在就整体跳过(对 starter 来说通常恒成立,但按惯例写上);
  • @ConditionalOnMissingBean :兜底让位开关------使用方自定义了 GreeterService 类型的 Bean,starter 的默认实现自动退场;
  • @AutoConfiguration :3.0 起官方推荐的自动配置注解,内部组合了 @Configuration(proxyBeanMethods = false),并配合 @AutoConfigureBefore/After 参与排序。

所以"自定义 starter"并没有任何新机制,只是把 2.2 + 3.2 + 3.3 节的三个零件按约定组装一遍。

机制之外再补三条工程上的血泪经验,都是自定义 starter 落地时最常返工的地方。

第一,依赖方向要严格单向 :autoconfigure 模块对业务 API 的依赖必须声明成 compileOnly(Maven 的 provided/Gradle 的 compileOnly)加可选,业务类真正的引入交给使用方或 starter 空壳模块的 runtime 依赖。原因是条件评估机制的前提是"classpath 有没有这类是动态的"------如果 autoconfigure 强依赖业务类,@ConditionalOnClass 就永远成立,机制退化成死代码;反过来使用方没引实现类时,自动配置整体跳过、不会抛 NoClassDefFoundError,这才是 starter"引了就生效、不��不碍事"的正确姿势。

第二,Properties 类要挂编译期处理器 :spring-boot-configuration-processor 会在编译期读取 @ConfigurationProperties 类的字段,生成 spring-configuration-metadata.json,IDE 的自动补全和文档提示全靠它。少了这个处理器,使用者写 greeter.xxx 时没有任何提示,starter 的体验直接掉一档;而且元数据里的 deprecation 声明(属性改名后的过渡提示)也是靠它从 @DeprecatedConfigurationProperty 注解生成的。

第三,版本发布用 BOM 收口 :starter、autoconfigure、业务 API 三个模块的版本由一个 BOM(spring-boot-dependencies 风格的 pom)统一管理,使用方只依赖 BOM + starter 空壳。没有 BOM 时,autoconfigure 与业务 API 版本漂移导致的"条件类对不上"是第三方 starter 最常见的兼容性事故来源------症状就是 3.5 节手册里第二类失效,而根子在工程结构。

3.5 自动装配失效排查手册

机制全部讲完,把生产环境里高频出现的"自动装配失效"场景整理成一本手册。排查的总原则一句话:先查"有没有进候选",再查"条件为什么不过",最后查"Bean 是不是被别人顶掉了"------正好对应清单 → 过滤 → 让位三层结构。

第一类:压根没进候选名单。 症状是 ConditionEvaluationReport 里找不到 那个配置类(连 Negative matches 里都没有)。原因通常有三种:清单文件路径或文件名写错(META-INF/spring/ 目录下必须是注解全限定名命名的 .imports 文件);3.x 项目里还往 spring.factories 的老键里登记(2.2 节讲过,不报错但不生效);jar 没有真正进 classpath(mvn dependency:tree 里查依赖是不是被 exclusion 掉了、或者被 <optional>true</optional> 隔断)。这一类的共同特征是"报告里查无此人",一眼可辨。

第二类:进了候选,条件不过。 症状是报告 Negative matches 区有这个类,且写明了不匹配的条件和原因。高频情形按出现频率排:

  1. @ConditionalOnClass 要求的类不在 classpath------报告会精确列出缺哪个类。多半是 starter 没引、引的坐标错、或者引了别的同源库(引了 reactor-core 但没引 spring-boot-starter-webflux,Reactive 条件照样不过);
  2. @ConditionalOnProperty 的开关没配置或值不对------注意 matchIfMissing 默认 false(3.2 节全家桶表里提过);
  3. @ConditionalOnWebApplication 不满足------工具类 jar 被非 Web 启动器加载时常见;
  4. @ConditionalOnMissingBean 被顶掉------报告里这条显示在"matched 但 Bean 没注册"的位置,注意它可能出现在方法级 :类整体 matched,但某个 @Bean 方法因为容器里已有同类型 Bean 而没注册(四节 demo 场景二正是这样)。

第三种情形里还有个隐蔽分支值得单独点名:被你自己的 @Configuration 顶掉 。用户配置类里随手写了一个和 starter 同类型的 @Bean(哪怕意图完全不同),starter 里所有挂着 @ConditionalOnMissingBean 的默认 Bean 全体退场------ConditionalOnMissingBean 是按类型 匹配的,不看语义。线上排查这类问题时,ctx.getBeanProvider(类型).stream().map(Object::getClass) 一行代码就能把"容器里到底有谁"数出来。

第三类:进了候选、条件也过了,但行为不符合预期。 这一类最难查,因为装配本身没问题,问题出在顺序或环境:

  • 顺序问题 :两个自定义 starter 互相依赖对方的 Bean,但都没写 @AutoConfigureBefore/After------评估 @ConditionalOnMissingBean 时对方还没注册,双双误判"可以注册"。解法是补排序声明,或者改用 ObjectProvider 延迟解析;
  • 测试切片问题 :@WebMvcTest/@DataJpaTest 只加载部分自动配置,全量 .imports 里的类默认不进场(切片带自己的过滤清单),单测里"为什么这个 Bean 没有"多半是这个原因,用 @ImportAutoConfiguration 显式补;
  • 类加载器问题 :devtools 的 RestartClassLoader 与条件评估的组合偶尔会让"同一类名的 Class"跨 loader 不相等,@ConditionalOnMissingBean 按类型匹配失败------devtools 的已知边界案例,生产 profile 关掉 devtools 即可。

把手册压成一张速查表贴在工位上:

症状 第一动作 对应机制章节
报告里查无此配置类 查 .imports 清单与依赖树 2.2
Negative matches 有明确原因 按缺类/缺配置/缺 Web 环境对症补 3.2
类 matched 但 Bean 没有 查方法级 @ConditionalOnMissingBean 被谁顶掉 3.3、四节
多 starter 之间 Bean 丢失 补 @AutoConfigureBefore/After 或改 ObjectProvider 3.1
单测里 Bean 缺失 确认测试切片范围,必要时 @ImportAutoConfiguration 3.5

四、Demo 实战验证

以上所有机制整理成一个可运行的 Maven 多模块工程 autoconfig-demo(SpringBoot 3.4.5 + JDK 17),结构如下:

text 复制代码
autoconfig-demo
├── greeter-spring-boot-autoconfigure   # 自动配置模块
│   ├── GreeterProperties / GreeterService / GreeterAutoConfiguration
│   └── META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
├── greeter-spring-boot-starter         # starter 空壳,只依赖 autoconfigure
└── app                                 # 使用方工程,依赖 starter

自动配置模块的核心代码:

java 复制代码
@AutoConfiguration
@ConditionalOnClass(GreeterService.class)
@ConditionalOnProperty(prefix = "greeter", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(GreeterProperties.class)
public class GreeterAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean   // 不带参数:默认按 @Bean 方法返回类型 GreeterService 匹配
    public GreeterService greeterService(GreeterProperties properties) {
        return new GreeterService(properties.getName(), "auto-configuration");
    }
}

使用方 app 里准备了两个开关场景,Runner 通过 ObjectProvider 拿 Bean(保证 Bean 缺失时不报错,走 else 分支),并在启动结束时直接打印 ConditionEvaluationReport 里与 Greeter 相关的条目:

java 复制代码
@SpringBootApplication
public class AutoconfigDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(AutoconfigDemoApplication.class, args);
    }

    // 场景二开关:app.custom-greeter=true 时,用户自定义的 GreeterService 注册进容器
    @Bean
    @ConditionalOnProperty(name = "app.custom-greeter", havingValue = "true")
    public GreeterService customGreeterService() {
        return new GreeterService("陈皮", "user-defined");
    }

    @Bean
    public CommandLineRunner verify(ApplicationContext context) {
        return args -> {
            // 1. 观察 GreeterService 到底是谁注册的
            ObjectProvider<GreeterService> provider = context.getBeanProvider(GreeterService.class);
            GreeterService service = provider.getIfAvailable();
            System.out.println(">>> GreeterService = " + (service == null ? "不存在" : service.greet()));

            // 2. 打印 ConditionEvaluationReport 中 Greeter 相关的评估结果
            ConditionEvaluationReport report = ConditionEvaluationReport.get(
                    ((ConfigurableApplicationContext) context).getBeanFactory());
            report.getConditionAndOutcomesBySource().forEach((configClass, outcomes) -> {
                if (configClass.contains("Greeter")) {
                    System.out.println(">>> " + configClass + " -> " + outcomes.isFullMatch());
                    outcomes.forEach(cno -> System.out.println(
                            "        " + cno.getOutcome().isMatch() + " | " + cno.getOutcome().getMessage()));
                }
            });
        };
    }
}

三种启动方式,分别对应三个场景:

bash 复制代码
# 场景一:默认启动,验证自动注入
mvn spring-boot:run -pl app
# 场景二:用户自定义 Bean,验证 Boot 让位
mvn spring-boot:run -pl app -Dspring-boot.run.arguments=--app.custom-greeter=true
# 场景三:条件不满足(greeter.enabled=false),--debug 打印条件评估报告
mvn spring-boot:run -pl app -Dspring-boot.run.arguments=--greeter.enabled=false,--debug

实测结果与源码分析逐条对应:

场景 启动参数 GreeterService 来源 实测输出(Runner + ConditionEvaluationReport) 印证的机制
一 无 自动配置注册 >>> GreeterService = Hello, Greeter! (by auto-configuration);报告 GreeterAutoConfiguration#greeterService -> true .imports 清单 + @ConditionalOnMissingBean 匹配(容器无该类型)
二 --app.custom-greeter=true 用户自定义 >>> GreeterService = Hello, 陈皮! (by user-defined);报告 greeterService 一行 @ConditionalOnMissingBean ... found beans of type 'GreeterService' customGreeterService @ConditionalOnMissingBean 让位 + deferred 保证评估时用户 Bean 已注册
三 --greeter.enabled=false --debug 不存在 >>> GreeterService = 不存在;报告 Negative matches 中 @ConditionalOnProperty (greeter.enabled) found different value in property 'enabled' @ConditionalOnProperty 不满足 + ConditionEvaluationReport 报告

场景二值得展开一句:报告里 GreeterAutoConfiguration 类本身是 matched(类级条件都满足),但 greeterService 这个 @Bean 方法因为方法级 ConditionalOnMissingBean 不匹配而没有注册------同一个配置类里"类级条件整体放行、方法级条件逐个让位",两道关卡各司其职,这就是 Boot "既兜底又可替换"的微观实现。

场景三的控制台里能直接看到 CONDITIONS EVALUATION REPORT 的结构:Exclusions(被 exclude 的)、Negative matches(条件不满足的,带原因)、Positive matches(生效的)。以后 starter 不生效,第一反应就应该是打开这个报告。

读报告本身也有讲究,三个区块的语义并不对称,排查时要区别对待:Exclusions 里的类在 getAutoConfigurationEntry 第 4 步就被剔除,条件评估压根没跑过 ,对应的排查方向是"谁把它 exclude 了"(注解属性还是 spring.autoconfigure.exclude 配置);Negative matches 里的类走完了条件评估但没过,每一行都带具体的失败条件和原因(缺哪个类、哪个属性值不对),是对症下药的主战场;Positive matches 则值得反着用------确认"你以为生效的配置"真的在里面,避免"以为 Boot 会配、其实条件早就没过、靠业务代码碰巧跑通"的隐性依赖。这份报告在测试里也能编程读取(demo 的 Runner 就示范了 ConditionEvaluationReport.get(beanFactory)),把它接进 CI 断言,装配行为就成了可回归验证的契约。

除了跑应用观察,demo 里还准备了官方推荐的自动装配单元测试 写法------ApplicationContextRunner。它是 spring-boot-test 提供的轻量容器外壳,专门用来把"某个自动配置类 + 某组条件"放进一个毫秒级启动的迷你容器里验证,不需要拉起整个 SpringApplication:

java 复制代码
class GreeterAutoConfigurationTest {

    private final ApplicationContextRunner runner = new ApplicationContextRunner()
            .withConfiguration(AutoConfigurations.of(GreeterAutoConfiguration.class));

    @Test
    void 默认启动时自动注册() {
        runner.run(context -> {
            assertThat(context).hasSingleBean(GreeterService.class);
            assertThat(context.getBean(GreeterService.class).greet()).contains("Greeter");
        });
    }

    @Test
    void 用户自定义Bean时自动配置让位() {
        runner.withBean("customGreeterService", GreeterService.class,
                        () -> new GreeterService("陈皮", "test"))
              .run(context -> {
                  assertThat(context.getBean(GreeterService.class).greet()).contains("陈皮");
              });
    }

    @Test
    void 开关关闭时不注册() {
        runner.withPropertyValues("greeter.enabled=false")
              .run(context -> assertThat(context).doesNotHaveBean(GreeterService.class));
    }
}

三个用例分别把第 2.3 节的清单机制、第 3.2 节的两阶段条件评估压缩成了毫秒级断言,而且 ApplicationContextRunner 还能直接输出条件评估报告(context.getStartupSteps() 与 ConditionEvaluationReport 均可拿),配合 withPropertyValues 模拟任意配置组合。给自定义 starter 配上这组测试,条件注解的时序问题(比如忘记 @AutoConfigureAfter 导致 @ConditionalOnMissingBean 评估顺序不对)能在 CI 里直接暴露,而不是等到用户项目里"玄学失效"。Boot 官方 autoconfigure 模块自己的几千个测试用例,几乎全是这个模式写成的------这也是读 Boot 测试源码时非常值得模仿的一手。

demo 里还准备了第四个场景------排除实验 ,验证 2.3 节流水线的第 4 步。先补齐排除的三种写法与优先级:@SpringBootApplication(exclude = XxxAutoConfiguration.class)(编译期类型安全,还能写 excludeName 以字符串排除"类不在 classpath"的场景)、@EnableAutoConfiguration 上同样的属性(粒度到单个配置类)、以及配置文件里的 spring.autoconfigure.exclude=类全名,类全名(运行时可配、可按 profile 切换,但只接受类名字符串)。三个来源在 getExclusions() 里汇成同一个集合(2.3 节源码可见),注解写法优先级更高只是因为它的内容也会出现在元数据里被工具校验。还有一个边界必须记牢:exclude 只对自动配置类有效 ------ConfigurationClassFilter 之前的校验只保证"排除的是已知自动配置类",而你自己的 @Configuration 类根本不在 .imports 清单里,想控制它们的注册只能走条件注解(@ConditionalOnProperty 之类)或 @Profile,写进 exclude 不会有任何效果也没有任何提示:

bash 复制代码
# 排除单个自动配置类(配置项方式)
mvn spring-boot:run -pl app -Dspring-boot.run.arguments=\
"--spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"

启动后观察报告:Exclusions 区出现 WebMvcAutoConfiguration,说明它在 getExclusions() 阶段就被剔除、根本没走到条件评估;如果排除一个不存在 的类名,checkExcludedClasses 会以「不修改运行时行为、仅记录」的方式容忍(排除的是无效类名不会报错),而排除一个别的自动配置类还依赖的类 (比如把 DispatcherServletAutoConfiguration 排掉后 WebMvcAutoConfiguration 里 @ConditionalOnBean(DispatcherServlet.class) 的下游 Bean 缺位),则会在启动或首次请求时以缺 Bean 的形式暴露------这也是为什么生产上做"排除某个 starter 的默认行为"改动时,一定要先跑一遍全量启动验证,排除的影响面是沿着条件链传播的,不是一行配置就能框死的。

最后用一张图把本文的知识点归纳一下:

五、总结

自动装配 = @EnableAutoConfiguration 导入的 AutoConfigurationImportSelector(一个 DeferredImportSelector)在配置类解析的最后阶段 批量读取所有 jar 的 AutoConfiguration.imports 清单,经去重、exclude、两级条件过滤后,把幸存的自动配置类递归交给 processImports 注册进容器;类级 @ConditionalOnClass 决定"配不配",方法级 @ConditionalOnMissingBean 决定"让不让位",deferred 机制保证了用户配置永远优先、Boot 只做兜��。

最后把本文放进专栏的知识网络里收个尾。(一)的 run() 全景给出了"配置文件 → Environment → 环境-ready → refresh"的骨架,(二)到这里补上了 refresh 内部最重的一块:ConfigurationClassPostProcessor 拿到配置类清单后,@ComponentScan 管你的代码、@Import 管显式导入、deferred 的自动装配管整个 classpath------三条装配来源在同一个解析器里汇流,然后交给(三)之后的 Bean 生命周期逐个实例化。自动装配的特殊性不在"注册 BeanDefinition"这个动作(那和普通扫描没区别),而在进场时机的延后与进场前的双层筛选:一张静态全量清单、两级 classpath 探测、两阶段条件评估、一套去中心化的排序约定。把这四样看懂,你面对任何 starter 源码------不管是官方两百多个还是公司内部中间件团队的封装------都能在十分钟内读出装配骨架;反过来自己动手写 starter 时,"清单、条件、Properties、排序声明"四件套缺一不可的依据也全在本文里。

最后把高频面试问答压成一张速记表,答案都能在前文源码里找到落点:

面试官问 一句话答(源码依据)
自动装配的核心流程? 配置类解析尾声,DeferredImportSelectorGrouping 统一执行 getAutoConfigurationEntry():读 .imports 清单 → 去重/排除 → 过滤器预筛 → 条件评估 → 递归注册(2.3、3.1 节)
为什么用 DeferredImportSelector? 让用户配置先解析注册,自动配置最后进场,@ConditionalOnMissingBean 才能正确"让位"(3.1 节)
@ConditionalOnClass 引用了不存在的类为什么报错? 条件评估基于 ASM 字节码元数据 + 字符串探测,类根本没加载;组合注解场景须用 name 属性(3.2 节)
@EnableWebMvc 后默认配置为什么全没了? 它导入的配置继承 WebMvcConfigurationSupport,触发类级 @ConditionalOnMissingBean 整体让位(3.3 节)
自定义 WebMvcConfigurer 为什么不冲突? 走委托收集(DelegatingWebMvcConfiguration 收集所有 WebMvcConfigurer),不是让位机制(3.3 节)
排查自动配置不生效的第一步? --debug 看 ConditionEvaluationReport 的 Negative matches 原因,或用 ApplicationContextRunner 写最小复现(3.2、四节)
自定义 starter 要做哪几件事? autoconfigure 模块(配置类 + Properties + .imports 清单)+ starter 空壳模块,条件注解三件套写全(3.4 节)
proxyBeanMethods = false 是什么取舍? 免 CGLIB 代理提启动速度,代价是配置类内 @Bean 方法互调不走容器(3.3 节)

下一篇我们分析启动链路上另一个核心环节:refresh 的 onRefresh() 里内嵌容器是怎么起来的------ServletWebServerFactory 与 Tomcat 的启动过程,看看 spring-boot-starter-web 里那个"不用装 Tomcat 也能跑"的魔法。


Demo 完整代码 :SpringBoot/B02-自动装配/autoconfig-demo(SpringBoot 3.4.5 + JDK 17,三个模块,按第四节命令逐场景启动验证)

专栏往期:

本文为「源码学习」专栏系列文章,转载请注明出处。相互学习,共同进步!

相关推荐
智购科技自动贩卖机10 分钟前
自动售货机SaaS多租户数据库实战:分库分表与租户隔离~YH
android·java·linux·开发语言·javascript·网络
沐知全栈开发1 小时前
基于SpringBoot的费用报销审批管理系统-毕业设计
spring boot·后端·课程设计
海宇大数据1 小时前
零信任架构实战:基于海宇企业股权变更构建自动化对公贷后股权异动监测网关
java·人工智能·架构·自动化
伊布拉西莫1 小时前
从静态参数到动态复用:Jenkins Parameters、Active Choices 与 Scriptler 实战指南
java·servlet·jenkins·devops
RuoyiOffice1 小时前
Vue3商城后台实战:一款商品,从规格上架走到部分退款
vue.js·spring boot·vue3·商城系统·商城·企业管理·ruoyi office
FYKJ_20101 小时前
Springcloud校园访客系统95346-计算机毕业设计、课程设计
java·spring boot·后端·spring·spring cloud·架构·课程设计
啊哈一半醒4 小时前
Go Web 开发知识点详解:从 HTTP 原理到 Gin 框架
后端·go·gin
想不到一个好的ID10 小时前
Redis Cluster
后端
EatFan10 小时前
Spring Boot 4.0 升级清单:JDK 基线、Jakarta 命名空间、Observation API 与第三方组件兼容一次讲清
java·spring boot·后端