第42章 卷十二 · 看料下单 · 为什么我的 Bean 没生效
- ⾃定义 starter 的最⼩件清单: @AutoConfiguration 类( proxyBeanMethods 恒为 false )+ META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports + @ConfigurationProperties (⽤你⾃⼰的命名空间)+ 条件注解;命名⽤ xxx-spring-boot-starter ,且必须直接或间接引到 spring-boot-starter 。
承上启下到这⾥,"看你带了什么料,⾃动给你配好产线"这条链算是⾛完了⼀整圈:清单(starter)把料备⻬ → BOM 把版本对⻬ → .imports 把候选摊在桌上 → 条件注解筛掉不该下的单 → 存活的 @AutoConfiguration 造出器来。
链路很漂亮。可它有⼀个致命的副作⽤:它太⻓了。
清单是别⼈写的,版本是 BOM 定的,候选是全 classpath 枚举来的,条件是在你看不⻅的地⽅⼀条条求值的,最后谁赢谁输还要看 @ConditionalOnMissingBean 的时序。这条链上任何⼀环出岔⼦,你在应⽤⾥看到的现象都只有⼀个——那个 Bean 就是没出来。
不报错、不警告、不留痕迹。你 @Autowired 拿到 null ,或者启动直接失败说找不到候选,然后你开始怀疑⼈⽣:是 starter 没引对?是版本冲突?是条件没命中?是被别⼈的 @ConditionalOnMissingBean 抢先了?还是——它其实⽣效了,只是被套了个壳,⽽你调的那⼀下根本没经过壳?
下⼀章,我们把这条链倒过来⾛。ch41:为什么我的 Bean 没⽣效。 我会给你⼀套不靠猜的排查法——从 --debug 打出的那份⾃动配置报告开始,⼀直查到条件求值的每⼀条判据。这是全书最实⽤的⼀章,也是"魔法"必须付出的那笔账。
为什么我的 Bean 没⽣效「它不报错、不警告、不留话。它只是不在。 ——但坊⾥其实记了账,只是那本账默认锁在抽屉⾥。」
开场:⼀桩"器凭空消失"的案⼦我在成器坊当稽核员这些年,接到最多的报案只有⼀句话:
"我明明写了 @Bean ,为什么它没⽣效?"
报案⼈通常已经做过三件事:把代码看了五遍、重启了⼗次、把 IDE 缓存清了。这三件事的共同点是——它们都在猜。
前⾯三章我们把机制拆开了:清单是⽂本、粗筛靠元数据、条件是⼀票否决、⾃动配置总在最后才注册。这些机制单独看都很清晰,但它们叠在⼀起,就构成了⼀条⻓到⽆法靠脑补⾛完的链路。链路⼀⻓,⼈就开始猜;⼀开始猜,排查时间就从⼗分钟变成⼀下午。
这⼀章不讲新机制。这⼀章只做⼀件事:把前三章的机制翻译成⼀套能上⼿的查案流程。
先⽴⼀条规矩,本章从头到尾不会动摇:
本坊记了账。账本叫 ConditionEvaluationReport 。任何"为什么没⽣效"的问题,第⼀步都是去翻那本账——⽽不是去猜。
⼀、先把病分对:三种"没⽣效"是三种病在翻账之前,得先把症状分类。我⻅过太多⼈拿着 A 病的症状去查 B 病的药。
病⼀:图纸就没进图纸库。 BeanDefinition 压根没注册。容器⾥根本不存在这个东⻄的"说明书"。注⼊时抛的是 NoSuchBeanDefinitionException ,消息是 "Noqualifying bean of type '...' available" ( [framework] spring-beans/src/main/java/org/springframework/beans/factory/NoSuchBeanDefinitionException.java:88 )或者 "No bean named '...' available" ( :49 )。
病⼆:图纸进了,但器没造出你要的那件。 定义在,但被同名定义覆盖了;或者被另⼀个候选抢了注⼊位;或者作⽤域/懒加载让它还没成形。
病三:器造了,你⼿上的却不是它。 递到你⼿上的是套了壳的原件(或者本该套壳却没套上)。这类症状最阴—— @Transactional 静默不回滚、 @Cacheable 每次都穿透、@Async 变成同步。⽅法调⽤发⽣了,只是没经过壳。
三种病,三把⼯具:
病 ⾸选⼯具图纸没进库 条件求值报告( --debug )+ 启动失败分析器图纸进了但选错/被覆盖 actuator beans 端点 + BeanDefinitionOverrideException
器造了但壳不对 断点看 getClass().getName() ⾥有没有 $$SpringCGLIB$$本章的绝⼤部分篇幅给第⼀种——因为它最常⻅,也因为它是唯⼀⼀种坊⾥已经把答案写好了、只是你没去读的病。


⼆、账本本体:⼀个"不是 Bean 的 Bean"
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java:181-194
public static ConditionEvaluationReport get(ConfigurableListableBeanFactory beanFactory) {
synchronized (beanFactory) {
ConditionEvaluationReport report;
if (beanFactory.containsSingleton(BEAN_NAME)) {
report = beanFactory.getBean(BEAN_NAME, ConditionEvaluationReport.class);
}
else {
report = new ConditionEvaluationReport();
beanFactory.registerSingleton(BEAN_NAME, report); // ←直接塞单例,不⾛ BeanDefinition
}
locateParent(beanFactory.getParentBeanFactory(), report);
return report;
}
}做了什么:拿⼀个挂在 beanFactory 上的单例账本,没有就现场造⼀个塞进去。bean 名写死在 :55 : "autoConfigurationReport" 。
为什么这么设计:注意它⽤的是 registerSingleton ⽽不是注册⼀条 BeanDefinition 。这不是随⼿写的——这本账记录的正是"哪些 BeanDefinition 活下来了、哪些没有",它必须⽐ BeanDefinition 体系本身更早存在。如果账本⾃⼰也是⼀条 BeanDefinition,就会掉进"要⽤账本先得有账本"的循环。
精妙处: locateParent ( :196-200 )会把⽗上下⽂的账本挂上来。主上下⽂和 management 上下⽂是⽗⼦关系时,两本账是串起来的——这是后⾯ actuator 端点能沿着上下⽂链⼀路吐出来的前提。
坑在哪:这个 bean 名叫 autoConfigurationReport 。名字是诚实的——它是⾃动配置的账本,不是容器的账本。 这句话请记牢,⼆⼗⾏之后我要拿它当⼑。
三、四栏账:Positive / Negative / Exclusions / Unconditional报告的渲染只有⼀个类,四栏顺序写死:
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportMessage.java:62-66
Map<String, ConditionAndOutcomes> shortOutcomes = orderByName(report.getConditionAndOutcomesBySource());
logPositiveMatches(message, shortOutcomes);
logNegativeMatches(message, shortOutcomes);
logExclusions(report, message);
logUnconditionalClasses(report, message);标题默认是 "CONDITIONS EVALUATION REPORT" ( :48 )。四栏各⾃说什么,我按"你该怎么⽤它"来讲,不按"它是什么"。
Positive matches:这⾥的东⻄⽣效了
分栏依据是 ConditionAndOutcomes.isFullMatch() ( :76 ,实现在 ConditionEvaluationReport.java:235-243 )——⼀个 source 上挂的所有条件全部 match,才算positive。
它的⽤法是反着⽤的:你要找的东⻄如果在这⼀栏,说明"没⽣效"这个前提本身就错了,你该去查病⼆或病三。别在这栏浪费时间找原因。
Negative matches:答案在这⼀栏[boot] .../logging/ConditionEvaluationReportMessage.java:163-186(节选)
message.append(String.format("%n %s:%n", source));...
message.append(String.format(" Did not match:%n"));
for (ConditionAndOutcome nonMatch : nonMatches) { logConditionAndOutcome(message, " ", nonMatch); }
if (!matches.isEmpty()) {
message.append(String.format(" Matched:%n"));...
}每条 negative 记录⻓这样(缩进是真的,我照源码的 %n / / 抄的):
RedisAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class 'org.springframework.data.redis.core.RedisTemplate'
Matched:
- @ConditionalOnBooleanProperty ... matched
读法:只看 Did not match 下⾯那⼏⾏。这就是答案本身,不是线索。 ConditionMessage 那套英语造句 DSL 造出来的话,是可以直接当结论读的:
did not find required class 'X' → 你少了个依赖。
found beans of type 'X' myBean → 有⼈先占了位;构造这句话的是 createOnMissingBeanNoMatchReason ( [boot].../condition/OnBeanCondition.java:436-448 ), myBean 就是抢位者的 bean 名,直接就是嫌疑⼈名单。
did not find any beans of type X → 你以为会有的前置 Bean 没有;来⾃ createOnBeanNoMatchReason ( :416-422 )。
@ConditionalOnProperty (foo.bar.enabled) did not find property 'enabled' → 属性没配或前缀错。还有⼀类记录⻓得很怪,值得单独说:
SomeAutoConfiguration$InnerConfiguration:
Did not match:
- Ancestor com.example.SomeAutoConfiguration did not match
这条不是真的求过值。它是补种的:
[boot] .../condition/ConditionEvaluationReport.java:126-135
private void addNoMatchOutcomeToAncestors(String source) {String prefix = source + "$";
this.outcomes.forEach((candidateSource, sourceOutcomes) -> {
if (candidateSource.startsWith(prefix)) {
ConditionOutcome outcome = ConditionOutcome.noMatch(
ConditionMessage.forCondition("Ancestor " + source).because("did not match"));
sourceOutcomes.add(ANCESTOR_CONDITION, outcome);
}
});
}做了什么:外层配置类被否决时,它的所有 static 内部类(JVM ⾥叫 Outer$Inner )其实根本没被求值过。如果不管,报告⾥这些内部类会显示成"⼀条否定条件都没有",看起来像是该⽣效的。于是渲染前做⼀次纯字符串前缀匹配,把"祖上被否了"这个事实补种进去。
ANCESTOR_CONDITION 是个哨兵( :57 ),它的 matches() 直接 throw new UnsupportedOperationException() ( :307-314 )——它只是个标签,永远不会被执⾏。为什么这很重要:Spring Boot 的⾃动配置⼤量使⽤"⼀个 @AutoConfiguration 套 N 个 static 内部 @Configuration "的写法(原因⻅上⼀章:为了隔离 @Bean ⽅法返回类型的加载)。如果没有这段补种,⼏乎每份报告都会有⼀堆看不懂的"⽆条件被跳过"的内部类。读到 Ancestor X did not match ,就该⽴刻掉头去 negative 栏⾥找 X 本身。
Exclusions:是你⾃⼰(或某个 starter)主动关掉的这⼀栏来⾃ recordExclusions ( ConditionEvaluationReport.java:95-98 ),数据由 ConditionEvaluationReportAutoConfigurationImportListener 灌⼊。三个来
源: @SpringBootApplication(exclude=) 、 excludeName= 、 spring.autoconfigure.exclude 。读法:如果你要找的⾃动配置在这⼀栏,别再查条件了——去 grep 全项⽬的 exclude 。⽽且要注意上⼀章那条:排除是全局的,多个 @EnableAutoConfiguration 场景下,别⼈写的 exclude 会连你的⼀起⼲掉。
Unconditional classes:减法算出来的[boot] .../condition/ConditionEvaluationReport.java:105-108, 86, 149-153
public void recordEvaluationCandidates(List<String> evaluationCandidates) {...
this.unconditionalClasses.addAll(evaluationCandidates); //先把所有候选塞进去
}// recordConditionEvaluation⾥:
this.unconditionalClasses.remove(source); // :86被评判过就移出去// getUnconditionalClasses返回时再减去 exclusions做了什么:所有候选 − 被任何条件评判过的 − 被排除的 = 从头到尾没⼈拦过的那些。它们⼀定⽣效。这⼀栏平时没⽤,但当你怀疑"某个⾃动配置是不是根本没有条件保护、⽆论如何都会插⼀脚"时,它是唯⼀的去处。
四、怎么把这本账打开:三个开关,各有各的脾⽓开关⼀: --debug (最常⽤,也最吵)
链路我逐环核过了:
- ConditionEvaluationReportLoggingListener 作为 ApplicationContextInitializer 注册在 [boot] core/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories:2-4 。
- 它默认⽤ DEBUG 级别——这是⽆参构造写死的:
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java:57-58
public ConditionEvaluationReportLoggingListener() {
this(LogLevel.DEBUG);
}- --debug 之所以能打开它,是因为它落在 org.springframework.boot 这个包前缀下:
[boot] core/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java:165-168
loggers.add(LogLevel.DEBUG, "sql");
loggers.add(LogLevel.DEBUG, "web");
loggers.add(LogLevel.DEBUG, "org.springframework.boot");
loggers.add(LogLevel.TRACE, "org.springframework");
判定 debug 是否开启的逻辑很松: value != null && !value.equals("false") ( :323-326 )。所以 --debug 、 -Ddebug 、 debug=true 、甚⾄ debug=whatever 都算开。
⚠ 这⾥有本章第⼀条真实批评。 --debug 会把 sql 、 web 、整个 org.springframework.boot ⼀起调到 DEBUG。为了看⼀份两百⾏的报告,你要先淹在⼏千⾏启动⽇志
⾥。Boot 没有提供"只打条件报告"的官⽅开关—— forLogLevel(...) ( :78 )是个 public 静态⼯⼚,但你得⾃⼰ new SpringApplication 再 addInitializers ,替换掉 spring.factories ⾥那个默认实例,属于绕路。
⼀条更省事的路⼦(这是我从源码推出来的,不是⽂档写的,⽤之前请⾃⼰验⼀次): ConditionEvaluationReportLogger ⾥ private final Log logger =
LogFactory.getLog(getClass()); ( [boot] .../logging/ConditionEvaluationReportLogger.java:39 ),⽽这个类是包私有、⽆⼦类,所以 getClass() 恒等于它⾃⼰。也就是说⽇志名就是 org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLogger , 把这⼀个 logger 单独调到 DEBUG,理论上就能只拿报告、不带⼀身⽇志。
开关⼆:启动失败时的⾃动降级(不⽤你开)
[boot] .../logging/ConditionEvaluationReportLogger.java:81-84
private void logMessage(String logLevel) {
this.logger.info(String.format("%n%nError starting ApplicationContext. To display the "
+ "condition evaluation report re-run your application with '%s' enabled.", logLevel));
}这句⼈⼈⻅过。它的触发条件是:启动崩了,⽽ DEBUG 没开( logReport(true) ⾥的 else if (isCrashReport) 分⽀, :71-76 )。
真正讲究的是它的前置准备:
[boot] .../logging/ConditionEvaluationReportLoggingListener.java:96-101
if (context instanceof GenericApplicationContext) {// Get the report early when the context allows early access to the bean// factory in case the context subsequently fails to load
ConditionEvaluationReport report = getReport();
reportSupplier = () -> report;
}为什么这么设计:这个 listener 监听的是 ContextRefreshedEvent 或 ApplicationFailedEvent ( :124-125 )。后者发⽣时上下⽂已经废了,再去 getBeanFactory()
拿报告可能拿不到。于是在构造 listener 的时刻——上下⽂还健康的时候——就把引⽤抓在⼿⾥。
这是全套诊断设施⾥我最欣赏的⼀处:诊断⼯具最容易失效的时刻,恰恰是最需要它的时刻。Boot 在这⾥提前把绳⼦系好了。
开关三:Actuator 的 conditions 端点(⽣产环境⽤这个)
[boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java:55, 64-72
@Endpoint(id = "conditions")
public class ConditionsReportEndpoint {@ReadOperation
public ConditionsDescriptor conditions() {
Map<@Nullable String, ContextConditionsDescriptor> contextConditionEvaluations = new HashMap<>();
ConfigurableApplicationContext target = this.context;
while (target != null) {
contextConditionEvaluations.put(target.getId(), new ContextConditionsDescriptor(target));
target = getConfigurableParent(target);
}
return new ConditionsDescriptor(contextConditionEvaluations);
}做了什么:沿 getParent() 把整条上下⽂链⾛⼀遍,每个上下⽂吐⼀份,带 parentId ( :124 )。返回的 JSON 结构和⽇志报告的四栏是同构的: positiveMatches /negativeMatches / exclusions / unconditionalClasses ( :107-115 )。
⚠ 默认值必须说清楚,这是全书最容易被⽹上⽂章带偏的⼀条: conditions 端点默认不暴露。实测 [boot] module/spring-boot-actuator-
autoconfigure/src/main/resources/META-INF/additional-spring-configuration-metadata.json :
management.endpoints.web.exposure.include → defaultValue: ["health"]management.endpoints.jmx.exposure.include → defaultValue: "health"
Web 和 JMX 默认都只暴露 health ⼀个。要⽤,必须显式写:
management:
endpoints:
web:
exposure:
include: health,conditions,beans,configprops注意"启⽤"和"暴露"是两件事,卡住你的是后者。端点⾃动配置本身只要 @ConditionalOnAvailableEndpoint 过了就会建
( ConditionsReportEndpointAutoConfiguration.java:34-39 ),它甚⾄⽤了 @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) ——只看当前上下⽂,不看⽗上下⽂,因为 management 上下⽂和主上下⽂是⽗⼦关系,⽤默认的 ALL 会被⽗上下⽂的同名 bean 误伤。这个细节本身就是"⽗⼦上下⽂会互相⼲扰"的活证据。
五、这本账的盲区(本章最重要的⼀段)
现在动⼑。
ConditionEvaluationReport 只记录"被条件评判过的东⻄"。
看 SpringBootCondition.matches 的记账动作( [boot] .../condition/SpringBootCondition.java:44-50 ):只有⾛进 Condition 的东⻄才会被recordEvaluation 。也就是说——你⾃⼰写的 @Service ,如果没被组件扫描扫到:报告⾥⼀个字都没有。既不在 positive,也不在 negative。
你⾃⼰写的 @Bean ,如果上⾯没挂任何 @Conditional :报告⾥⼀个字都没有。
你的 starter 的 .imports ⽂件写错了路径 / 没打进 jar:那条⾃动配置根本没进候选,报告⾥⼀个字都没有。
它的 bean 名叫 autoConfigurationReport ,名副其实:它是⾃动配置的账本,不是容器的账本。
所以本章的排查顺序,必须以"在不在账上"作为第⼀个分叉:
翻账,如果你要找的类根本不在这本账的任何⼀栏⾥——问题不在条件,在"它压根没被送进求值流程"。
这时该换⼯具:actuator 的 beans 端点( @Endpoint(id = "beans") , [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/beans/BeansEndpoint.java:43 )看容器⾥到底有什么; configprops (同仓.../context/properties/ConfigurationPropertiesReportEndpoint.java:72 )看属性绑成了什么; startup ( .../startup/StartupEndpoint.java:44 )看启动步骤。
六、排查顺序:⼀条决策树把上⾯的东⻄压成流程。这就是我在坊⾥贴在墙上的那张:
- 先分类:这东⻄是「我写的」还是「starter 给的」?
├─ 我写的 → ⼤概率是扫描/覆盖问题,直接跳 2
└─ starter 给的 → ⾛ 1- 加 --debug 启动,翻条件求值报告
├─ 在 Negative matches → 读 Did not match 那⼏⾏,它就是答案。完。
├─ 在 Exclusions → grep 全项⽬的 exclude / spring.autoconfigure.exclude。完。
├─ 在 Positive matches → 它⽣效了。你的病是⼆或三,跳 3。
├─ 只有 "Ancestor X did not match" → 回到 X 本身,重⾛这⼀步。
└─ ⼀个字都没有 → 它没被送进求值流程,跳 2。- 「没被送进流程」的四种可能
├─ 组件扫描没覆盖到这个包
├─ ⾃定义 starter 的 .imports ⽂件路径/内容不对
├─ ⾃动配置类被放进了扫描包内(会被 AutoConfigurationExcludeFilter 剔掉)
└─ 整个⾃动配置被关了(spring.boot.enableautoconfiguration=false)- 「⽣效了但⾏为不对」的三种可能
├─ 被同名定义覆盖 → 看 BeanDefinitionOverrideException / beans 端点
├─ 多候选选错 → 看 @Primary / @Qualifier / fallback
└─ 壳没套上 → 打印 getClass().getName(),看有没有 $$SpringCGLIB$$第 0 步不能省。 报告只对第 1 类有⽤,拿它去查第 2 类是⽩费⼒⽓——这正是上⼀节那把⼑的⽤处。
七、常⻅原因清单:七条,每条给坐标① 没被扫描到默认扫描包不是"整个项⽬",是声明 @ComponentScan 的那个类所在的包:
[framework] spring-context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java:116-119
for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
basePackages.add(ClassUtils.getPackageName(clazz));
}
if (basePackages.isEmpty()) {
basePackages.add(ClassUtils.getPackageName(declaringClass));
}坑:把启动类放在 com.example.app ,把服务放在 com.other ,就扫不到。
更隐蔽的坑,官⽅ javadoc 亲⼝写的:
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SpringBootApplication.java:86-89
* <strong>Note:</strong> this setting is an alias for
* {@link ComponentScan @ComponentScan} only. It has no effect on {@code @Entity}- scanning or Spring Data repository scanning. For those you should add
* {@code @EntityScan} and {@code @Enable...Repositories} annotations.scanBasePackages 只管组件扫描,管不了 @Entity 和 Spring Data repository 扫描——那两个⾛的是 @AutoConfigurationPackage 记下来的包(即启动类所在的包)。
所以"我加了 scanBasePackages 为什么 JPA 实体还是找不到"是个每年都会重演的经典误会。
还有⼀条反向的坑:别把⾃动配置类放进会被扫描的包。
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilter.java:51-65
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) {
return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader);
}
private boolean isAutoConfiguration(MetadataReader metadataReader) {
boolean annotatedWithAutoConfiguration = metadataReader.getAnnotationMetadata()
.isAnnotated(AutoConfiguration.class.getName());return annotatedWithAutoConfiguration


|| getAutoConfigurations().contains(metadataReader.getClassMetadata().getClassName());
}判据取或:标了 @AutoConfiguration ,或者名字出现在 .imports 清单⾥。命中就从扫描结果⾥剔掉。写⾃定义 starter 时,这个过滤器是你的朋友;但如果你的类既在扫描包内、⼜忘了写进 .imports ,它就会被当成普通 @Configuration ⽆条件注册——绕过全部排序和退让机制,⾏为会诡异得让⼈怀疑⼈⽣。
② 条件不满⾜去 negative 栏读理由。这⾥只补三条最容易记反的默认值,全部回源核实过:
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.java:135, 142
String havingValue() default "";
boolean matchIfMissing() default false;[boot] .../condition/OnPropertyCondition.java:182-187
private boolean isMatch(@Nullable String value, String requiredValue) {
if (StringUtils.hasLength(requiredValue)) {
return requiredValue.equalsIgnoreCase(value); // ←忽略⼤⼩写
}
return !"false".equalsIgnoreCase(value); // ← havingValue为空时:只要不是 false就算过
}matchIfMissing 默认 false :属性不存在 = 不匹配。这是被记反次数最多的⼀条。
havingValue 默认 "" :语义是"只要不等于 false ",不是"必须等于 true"。 foo.enabled=banana 是匹配的。
⽐较忽略⼤⼩写: TRUE 和 true 等价。
prefix 会⾃动补尾点( OnPropertyCondition.java:144-150 ),所以 prefix="foo" 和 prefix="foo." 等价。name 和 value 必须⼆选⼀、且不能同时给,否则启动直接失败,报 The name and value attributes of @ConditionalOnProperty are exclusive ( :158-162 )。
⚠ 本基线新增的⼀处语义分叉: @ConditionalOnBooleanProperty ( @since 3.5.0 )的 havingValue() 是 boolean 类型、默认 true ——它要求属性必须等于
true 。同⼀个 foo.enabled=banana , @ConditionalOnProperty 匹配、 @ConditionalOnBooleanProperty 不匹配。Boot 4 的⾃动配置已经在⼤量改⽤后者(⻅下⾯AopAutoConfiguration 的例⼦),⽹上关于 Boot 3 的⽂章在这⼀点上会误导你。
③ 被 @ConditionalOnMissingBean 让位或抢位这是⾃动配置的核⼼礼节,也是最容易出"我明明⾃⼰定义了却没⽤上"的地⽅。两条 reason ⽂案就是嫌疑⼈名单:
[boot] .../condition/OnBeanCondition.java:436-448(createOnMissingBeanNoMatchReason 节选)
reason.append("found beans ");
reason.append(description); // "of type" / "annotated with"
reason.append(" '");
reason.append(key);
reason.append("' ");看到 found beans of type 'javax.sql.DataSource' myDataSource ,就知道 myDataSource 是那个让⾃动配置退让的⼈。
三条容易漏看的过滤规则(全在 OnBeanCondition ):
@Bean(autowireCandidate = false) 或 defaultCandidate = false 的 Bean 会被条件⽆视( :280-300 的 isCandidate ;ConditionalOnMissingBean.java:74-75 javadoc 亲⼝写了)。于是"我明明定义了,⾃动配置还是⽣效了"。
FactoryBean 的产出可能被漏看:
[boot] .../condition/OnBeanCondition.java:334
result = putAll(result, beanFactory.getBeanNamesForType(type.resolvableType(), true, false), beanFactory);
// includeNonSingletons ↑ allowEagerInit = false ↑第三个参数 false 意思是"不为了确定 FactoryBean 的产出类型⽽去实例化它"。如果 FactoryBean 的泛型在 BeanDefinition 层⾯推不出来,@ConditionalOnMissingBean 就看不⻅它产出的 Bean,⾃动配置照样⽣效,最终容器⾥出现两个同类型 Bean。官⽅⽂档那句"在 @Bean ⽅法上尽可能给出完整类型信息",根就在这⾏的第三个参数上。
@ConditionalOnSingleCandidate 有四级判定阶梯( :168-200 ):恰好 1 个 → 过;恰好 1 个 @Primary → 过;多个 @Primary → 不过;恰好 1 个⾮ fallback →过;否则 found multiple beans 。
④ 顺序不对@AutoConfigureAfter / @AutoConfigureOrder 的 javadoc,两处⼀字不差地写着同⼀句:
"the order in which auto-configuration classes are applied only affects the order in which their beans are defined. The order in which those beans aresubsequently created is unaffected..."
只影响定义顺序,不影响创建顺序。 想控制创建顺序,得⽤依赖关系或 @DependsOn 。这条是被误解次数最多的⼀条。
⽽"定义顺序"恰恰是 @ConditionalOnMissingBean 的命根:两个⾃动配置之间⽤它,必须配 @AutoConfigureAfter ,否则谁赢取决于排序,是隐性时序耦合。javadoc 也承认了这个限制( ConditionalOnMissingBean.java:57-60 ):"it is strongly recommended to use this condition on auto-configuration classes only"。
推论(很多⼈栽在这):在你⾃⼰的 @Configuration 上写 @ConditionalOnMissingBean ⼏乎必错。 ⽤户配置类在 parse 早期就被处理,那时⾃动配置的 bean 定义⼀条都还没进 registry——你"看不⻅"任何⾃动配置的 Bean,条件永远为真。
⑤ 被覆盖
同名 Bean 的裁决全在⼀个⽅法⾥:
[framework] spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java:352-374(节选)
// A bean definition resulting from a component scan can be silently overridden// by an @Bean method - and as of 6.1, even when general overriding is disabled// as long as the bean class is the same.
if (existingBeanDef instanceof ScannedGenericBeanDefinition scannedBeanDef) {
if (beanMethod.getMetadata().getReturnTypeName().equals(scannedBeanDef.getBeanClassName())) {
this.registry.removeBeanDefinition(beanName);
}
return false;
}// Has the existing bean definition bean marked as a framework-generated bean?
if (existingBeanDef.getRole() > BeanDefinition.ROLE_APPLICATION) {
return false;
}
if (!this.registry.isBeanDefinitionOverridable(beanName)) {
throw new BeanDefinitionOverrideException(...);
}三条规则,注意第⼀条注释⾥的 "silently overridden"——组件扫描来的定义会被同类型的 @Bean ⽅法静默移除,⼀句⽇志都没有。这是设计意图(让 @Bean 能显式盖掉扫到的东⻄),但"静默"两个字确实值得警惕。
默认值(回源核实): spring.main.allow-bean-definition-overriding 默认 false —— [boot] core/spring-boot/src/main/java/org/springframework/boot/ApplicationProperties.java:43 的字段⽆初始值即 false ,配置元数据⾥也写着 "defaultValue": false ;⽣效点在 [boot] .../SpringApplication.java:390 。所以真撞上同名,多数情况是启动直接失败,⽽不是悄悄覆盖。失败时 Boot 会给⼀条完整的⼈话:
[boot] core/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BeanDefinitionOverrideFailureAnalyzer.java:33-34
private static final String ACTION = "Consider renaming one of the beans or enabling "
+ "overriding by setting spring.main.allow-bean-definition-overriding=true";别照着这条 ACTION ⽆脑改成 true 。 它是 Boot 给的逃⽣梯,不是推荐做法——打开它,你就把"启动即失败"换成了"运⾏期⾏为取决于注册顺序"。
⑥ 代理没⽣效这是病三,报告完全帮不上忙。三个⾼频原因:
⾃调⽤:同类内 this.method() ⾛的是原件⾃⼰的⽅法表,根本不经过壳。 @Transactional / @Cacheable / @Async 全部静默失效。壳是AbstractAutoProxyCreator 这个 BeanPostProcessor 在 postProcessAfterInitialization ( [framework] spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:285-290 )⾥把你造好的器换掉得到的——它只能拦住"从外⾯进来的调⽤"。
final 类 / final ⽅法:CGLIB 是"照原件仿造⼀个⼦件", final 的地⽅仿不了。⽽ Boot 默认就是 CGLIB:
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/aop/AopAutoConfiguration.java:61-64
@Configuration(proxyBeanMethods = false)
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", matchIfMissing = true)
static class CglibAutoProxyConfiguration {matchIfMissing = true = 不配就是 CGLIB。想换 JDK 动态代理,得显式 spring.aop.proxy-target-class=false ,⾛ :55-57 那个分⽀。(顺带:这⼀⼩段本身就是"⽤嵌套 @Configuration + 条件做⼆选⼀"的教科书样板,值得抄。)
proxyBeanMethods 的两⾯: @Configuration 的 proxyBeanMethods 默认 true ( [framework] spring-context/src/main/java/org/springframework/context/annotation/Configuration.java:477 ),配置类内部互相调 @Bean ⽅法会⾛壳、拿到同⼀个单例。但@AutoConfiguration 把它硬编码成了 false ——所以在⾃动配置类⾥ this.someBean() 是真的⼜ new 了⼀个。抄⾃动配置的代码时,这个差异会咬⼈。
⑦ 配置前缀写错[boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationProperties.java:78, 85
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;ignoreUnknownFields 默认 true 。 意思是:你在 yml ⾥写错⼀个字段名,不报错,不警告,那个值就是绑不上,字段留默认值。前缀写错更彻底——整个类的字段⼀个都绑不上,全是默认值,⽽应⽤照常启动。
⚠ 这是本章第⼆条真实批评,也是我认为整套体系⾥最⽋缺的⼀环。 Spring Boot 花了 449 ⾏写 ConditionMessage 只为了让报错读起来像⼈话,却在"配置项拼错"这个最⾼
频的错误上选择了静默。它不会告诉你"你写的 acme.foo 前缀在整个应⽤⾥没有任何 @ConfigurationProperties 认领",也不会告诉你"你这个 @ConditionalOnProperty的前缀在全部配置源⾥零命中"。整套诊断设施是"事后解释",不是"事前防御"——它能在你崩溃后告诉你为什么,但不会在你写错的那⼀刻拦住你。
排查⼿段只有⼀个: configprops 端点,看绑定后的实际值。看值,不要看你的 yml。
⼋、四个场景推演场景 A:启动就崩, NoSuchBeanDefinitionException这是最幸运的情况——因为 Boot 早就替你把账翻好了。
[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzer.java:69-76
NoSuchBeanDefinitionFailureAnalyzer(BeanFactory beanFactory) {...
this.metadataReaderFactory = new CachingMetadataReaderFactory(this.beanFactory.getBeanClassLoader());// Get early as won't be accessible once context has failed to start
this.report = ConditionEvaluationReport.get(this.beanFactory);
}做了什么:这个失败分析器持有条件求值报告。当有⼈注⼊不到 Bean 时,它做三件事:
- 遍历报告⾥所有 ⾮ fullMatch 的 source( :156-176 );
- 在这些被否决的配置类⾥,找返回类型或 bean 名对得上的 @Bean ⽅法( BeanMethods.isMatch , :249-260 );
- 把"这个⽅法本来会产出你要的 Bean,但它因为 XXX 没加载"拼成⼀⾏:
[boot] .../NoSuchBeanDefinitionFailureAnalyzer.java:308-311
return String.format("Bean method '%s' in '%s' not loaded because %s",
this.methodMetadata.getMethodName(),
ClassUtils.getShortName(this.methodMetadata.getDeclaringClassName()),
this.conditionOutcome.getMessage());它还会额外扫⼀遍 exclusions,给出 auto-configuration 'X' was excluded ( :178-188 )。
于是你在控制台看到的是这样⼀段(格式取⾃ :87-110 ,条件⽂案格式取⾃本仓测试 [boot] core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/diagnostics/analyzer/NoSuchBeanDefinitionFailureAnalyzerTests.java:150 ):
Parameter 0 of constructor in com.example.MyService required a bean of type'java.lang.String' that could not be found.The following candidates were found but could not be injected:
- Bean method 'string' in 'TestMissingBeanAutoConfiguration' not loaded because
@ConditionalOnBean (types: java.lang.Integer; SearchStrategy: all) did not find any beansAction:
Consider revisiting the entries above or defining a bean of type 'java.lang.String' in your configuration.它已经把答案直接写在你脸上了。 这段输出的信息量,等价于你⼿动翻半天报告。它注册在 [boot] core/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories:26-27 ,默认就在,不需要开任何开关。
所以场景 A 的正确姿势是:先把控制台往上翻,找那段带 Description: / Action: 的⽅框。 我⻅过太多⼈跳过它去看堆栈——那段⽅框才是 Boot 想跟你说的话。
场景 B:报告⾥明明是 positive,运⾏时却有两个同类型 Bean症状: @Autowired 报 NoUniqueBeanDefinitionException ,或者你的⾃定义 Bean 和⾃动配置的 Bean 同时存在。
推演:⾃动配置在 positive 栏,说明它的 @ConditionalOnMissingBean 判定为"没找到"。可你明明定义了。三个嫌疑:
- 你的 Bean 是 FactoryBean 产出的,泛型在定义层⾯推不出来 → allowEagerInit = false 让条件看不⻅它( OnBeanCondition.java:334 )。
- 你的 @Bean ⽅法返回类型写成了接⼝的⽗类型或 Object ,⽽条件是按⽅法签名的返回类型推断的( getReturnType , :690-698 ),推出来的类型对不上。
3. 你标了 @Bean(autowireCandidate = false) ( isCandidate , :280-300 )。修法优先级:先补类型信息(把 @Bean ⽅法返回类型写具体),这是官⽅推荐的第⼀⼿段;实在推不出来,才考虑给⾃动配置排 @AutoConfigureAfter 。
场景 C:加了依赖,报告⾥连这条⾃动配置的名字都没有推演:不在 negative、不在 positive、不在 exclusions、不在 unconditional——它根本没进候选清单。
回上⼀章的机制:候选来⾃ classpath 上所有 jar 的 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 。查三处:
- jar ⾥到底有没有这个⽂件( unzip -l xxx.jar | grep imports )。
- Boot 4 ⼤搬家了:本基线 spring-boot-autoconfigure 这个 jar 的 .imports 只剩 12 ⾏,其余全部下放到各 module/ 。包名也跟着变了( org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration →
org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration )。你 exclude= ⾥写的 Boot 3 ⽼类名,在 Boot 4 上不是"排除失败",⽽是可能触发 IllegalStateException ——因为 checkExcludedClasses 的规则是"类在 classpath 上存在、但不在候选清单⾥ → 抛异常"。
- ⾃定义 starter:类名写错、嵌套类没⽤ $ 、或者这个类被扫描包捡⾛了(回看原因 ①)。
场景 D(短): @ConditionalOnProperty 死活不匹配按顺序排除:前缀是否重复带了点( prefix="foo." + name="bar" 会拼成 foo.bar ,没问题;但 prefix="foo" + name=".bar" 会拼成 foo..bar );属性名是否⽤了dashed 写法(javadoc ConditionalOnProperty.java:121-122 明确要求"all lower case with a - ");是不是集合属性——javadoc 亲⼝承认这个注解对集合不可靠( :75-86 ): x.values 存在时匹配, x.values[0] 存在时不匹配,官⽅建议"改⽤⾃定义条件"。
🦴 ⻣灰级细节
报告的 key 是短类名,重名时才展开全名。 orderByName ( ConditionEvaluationReportMessage.java:130-147 )先把所有 source 按ClassUtils.getShortName 分组,只有⼀个的⽤短名当 key,多于⼀个的才全部⽤全限定名。所以你在报告⾥看到的 WebMvcAutoConfiguration 和看到的org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration 是两种不同的情况——后者意味着 classpath 上有同名的另⼀个类。这个细节能救你于"为什么这条记录格式跟别的不⼀样"的困惑。
getConditionAndOutcomesBySource() 是有副作⽤的。 第⼀次调⽤会触发祖先补种,并置 addedAncestorOutcomes = true ( :115-122 );⽽任何⼀次新的recordConditionEvaluation ⼜会把它重置为 false ( :88 )。所以这个 getter 不是纯读——它在懒计算。
getDelta ( :202-218 )做报告差分:只保留 isFullMatch() 结果发⽣变化的 source。这是 devtools 热重启时"这次和上次⽐,哪些⾃动配置变了"的实现基础。排查"改了个配置为什么⾏为全变"时,这是唯⼀的正规⼿段。
AOT 构建期也会打报告。 [boot] core/spring-boot-autoconfigure/src/main/resources/META-INF/spring/aot.factories ⾥注册了ConditionEvaluationReportLoggingProcessor 。native image 场景下条件在构建期就冻结了,运⾏期换 profile、加依赖都不会重新求值——所以那份构建期的报告才是权威的。
⚠ 暗礁
--debug 打开的不只是报告,还有 sql 、 web 、整个 org.springframework.boot 。⽣产上别这么⼲。
conditions / beans / configprops 端点默认全不暴露,默认只有 health 。⽽且这三个端点会吐出你的类名、Bean 名甚⾄配置值——暴露前想清楚谁能访问。
报告只覆盖⾛过 Condition 的东⻄。 没被扫描到的组件、没挂条件的 @Bean 、没进候选清单的⾃动配置,报告⾥⼀个字都没有。别指望它当容器的全量清单。
ConditionEvaluationReport 是 registerSingleton 出来的,不是普通 Bean。⾃定义 BeanFactory、AOT 等特殊场景下要注意它的可⻅性——
find(BeanFactory) ( :169-174 )在 beanFactory 不是 ConfigurableListableBeanFactory 时会返回 null,⽽不是抛异常。
别把 BeanDefinitionOverrideFailureAnalyzer 给的那条 spring.main.allow-bean-definition-overriding=true 当成修复⽅案。 它是逃⽣梯。⽤它的代价是把确定性的启动失败换成不确定性的运⾏期⾏为。
🎯 三句带⾛1. --debug 启动看 CONDITIONS EVALUATION REPORT 四栏;Negative matches 下的 Did not match 就是答案本身,不是线索。⽣产上⽤ actuator 的 conditions端点,但它默认不暴露(默认只暴露 health ),要显式加进 management.endpoints.web.exposure.include 。
- 这份报告只记"被条件评判过的东⻄",它的 bean 名 autoConfigurationReport 是诚实的。要找的类⼀个字都不在报告⾥,说明它没进求值流程——该查扫描包、 .imports 清单和 exclude,⽽不是继续读报告。
- 启动崩溃时先往上翻控制台找带 Action: 的⽅框: NoSuchBeanDefinitionFailureAnalyzer 已经替你翻过账,会直接告诉你「Bean method 'x' in 'Y' not loadedbecause ⟨条件原因⟩」。
承上启下到这⾥,"坊⾥为什么少了⼀件器"这类案⼦,你已经有了⼀整套查法:分病、翻账、读理由、按图索骥。
但有⼀类器,你从来不会问它"为什么没⽣效"——因为它⼀旦没⽣效,应⽤根本起不来:那个内嵌在坊⾥的⻔市。它不在你的图纸上,不在你的 @Bean ⾥,你甚⾄没写过⼀⾏关于它的代码,可 SpringApplication.run ⼀收⼯,8080 端⼝就开始应客。
这是本坊最反直觉的⼀处反转:过去是⻔市⾥摆个坊(把 war 丢进 Tomcat),现在是坊⾥开个⻔市。这个⻔市是怎么被造出来的、端⼝是怎么定下来的、优雅停机时它怎么知道该等谁;还有那扇专⻔开给外⼈看的窗⼝——体检窗⼝ Actuator,它凭什么能把坊⾥的家底⼀览⽆余,⼜凭什么默认只肯露出⼀个 health 。
下⼀章,我们进⻔市。