源码小说CodeStory
登录
上一章

30,478 字 · 约 76 分钟

下一章
字体

主题

版式

第40章 卷十二 · 看料下单 · 看料下单:@Conditional 家族

看料下单:@Conditional 家族"我只有⼀个⽅法,返回⼀个 boolean 。 我不解释、不记账、不留名。我说 false,那张图纸就没了——⾄于为什么没的,你⾃⼰猜去。" —— Condition 的⾃述上⼀章我们看⻅⾃动配置那⼀⼤摞图纸是怎么被推到最后才处理的。这⼀章要问的是更硬的⼀个问题:

这⼀百多张图纸⾥,凭什么只有那么⼏张落地?

答案是"看料下单"——料不在就不下这道单。听起来简单得像句废话。但只要你真动⼿写⼀次,就会撞上⼀堵墙:

@ConditionalOnClass(RedisTemplate.class)

这⾏代码要表达的意思是"如果 RedisTemplate 这个类不在类路径上,就当我没说"。可你为了说这句话,必须在源码⾥写下 RedisTemplate.class 这五个字。写下它,编译器就把这个类型记进了常量池;类加载器⼀读到它、⼀去解析,就得去找这个类——找不到, NoClassDefFoundError ,启动直接崩在你想避免的那件事上。

你正在⽤⼀个东⻄,来声明这个东⻄可能不存在。

这⼀章的主线,就是拆开这个悖论。⽽拆到最后你会发现,Spring 给出的答案不是什么⾼深的类加载技巧,⽽是⼀个近乎粗暴的决定:那就别⽤ JVM 的眼睛看类,⽤我们⾃⼰的眼睛看。

⼀、Framework 那⼀侧:493 ⾏,⼀个⽅法,只投票不解释先把地基交代清楚。整个 Framework 的条件机制有多⼤?我数了⼀下——五个⽂件,493 ⾏:

⽂件(均在 [framework] spring-context/src/main/java/org/springframework/context/annotation/ ) ⾏数 ⻆⾊Conditional.java 70 注解本体Condition.java 61 函数式接⼝,唯⼀⽅法 matchesConditionContext.java 67 给 Condition ⽤的"环境句柄"

ConfigurationCondition.java 61 带阶段的 ConditionConditionEvaluator.java 234 求值器——⽽且是包私有的493 ⾏,撑起了整个 Spring Boot。这是全书⾥投⼊产出⽐最夸张的⼀处。

1.1 注解本体:三条不起眼但要命的规矩// [framework] spring-context/src/main/java/org/springframework/context/annotation/Conditional.java:59-69

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Conditional {
Class<? extends Condition>[] value();
}

三件事要记住:

其⼀, @Target 只有 TYPE 和 METHOD。 没有 FIELD,没有 PARAMETER。想在某个构造器参数上做条件化注⼊?本坊不接这个活。

其⼆,类上打了 @Conditional ,整栋楼⼀起熄灯。 javadoc :41-44 写得很清楚:该类的所有 @Bean ⽅法、所有 @Import 、所有 @ComponentScan ⼀并受制。这是后⾯"嵌套 static 内部类"那套写法能成⽴的语义基础。

其三, @Conditional 不被继承。 javadoc :46-52 ⽤加粗的 NOTE 写着: Inheritance of @Conditional annotations is not supported 。⽗类上的条件、被覆盖的⽗类⽅法上的条件,⼀律不看。⽽且——为了把这条语义焊死, @Conditional ⾃⼰故意不标 @Inherited ,并且原⽂要求:你⾃⼰写的组合注解也不许标 @Inherited 。

这条规矩在实战⾥咬⼈的场景是:你写了个抽象配置基类,把 @ConditionalOnProperty 打在基类上,指望⼦类继承。不会的。⼀条都不会⽣效,⽽且不报错。

1.2 Condition :⼀个⽅法,两条戒律// [framework] spring-context/src/main/java/org/springframework/context/annotation/Condition.java:48-59@FunctionalInterface

public interface Condition {
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}

javadoc ⾥两条戒律要原样背下来:

戒律⼀( :30-31 ): Conditions must follow the same restrictions as a BeanFactoryPostProcessor and take care to never interact with beaninstances.条件求值发⽣在改图纸的阶段( ConfigurationClassPostProcessor 内部,也就是 BFPP 那⼀档)。此时坊⾥⼀个业务单例都还没造出来。你在 Condition ⾥⼿贱调⼀次getBean() ,轻则把某件器提前实例化、绕过⼀堆后置处理器(拿到的是没套壳的原件),重则死循环。

戒律⼆( :35-38 ):同⼀处的多个 Condition 按 Ordered / @Order 排序,⾛ AnnotationAwareOrderComparator 。

这条现在看着平淡,到 §3.3 你会发现它是 Boot 整个成本模型的物理保证。

另外注意 metadata 的类型是 AnnotatedTypeMetadata ——它运⾏时可能是 AnnotationMetadata (类上)也可能是 MethodMetadata ( @Bean ⽅法上)。这个"两态"贯穿了 Boot 条件家族的每⼀个实现类。

1.3 ⼼脏: shouldSkip() 的 30 ⾏

// [framework] spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java:81-106

public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
return false;
}
if (phase == null) {
if (metadata instanceof AnnotationMetadata annotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate(annotationMetadata)) {
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List<Condition> conditions = collectConditions(metadata);
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
if (condition instanceof ConfigurationCondition configurationCondition) {
requiredPhase = configurationCondition.getConfigurationPhase();
}
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
return true;
}
}
return false;
}

做了什么:收集条件 → 排序 → 挨个问 → 任意⼀个说 false,⽴刻 return true (跳过)。

四个必须记住的点:

  1. ⼀票否决 + 短路( :100-101 )。第⼀个投反对票的条件之后,后⾯的条件根本不执⾏。这不是性能优化的副产品,这是"类不存在也不炸"的第⼆道保险——@ConditionalOnClass 排在最前,它⼀挂,后⾯那些要碰 Bean、碰反射的条件压根没机会跑。
2. 阶段过滤( :100 ): requiredPhase == null || requiredPhase == phase 。普通 Condition (没实现 ConfigurationCondition )的 requiredPhase 是

null,意味着两个阶段都会被求值——同⼀个配置类上,你的⾃定义 Condition 会被调⽤两次。很多⼈第⼀次写 Condition 时"我的⽇志怎么打了两遍",根因就在这个null || 上。

3. 阶段能⾃动推断( :86-92 ):调⽤⽅不传 phase 时,⽤ ConfigurationClassUtils.isConfigurationCandidate() 判——有没有

@Component / @ComponentScan / @Import / @ImportResource ,或者有没有 @Bean ⽅法。

4. Condition 实例每次都新建,没有缓存。 getCondition() ( :137-140 )是 ClassUtils.resolveClassName + BeanUtils.instantiateClass ,⼀次求值 new ⼀

个。所以你的 Condition 实现类必须有⽆参构造,且不许在字段⾥存状态。

顺带⼀句: collectConditions() 在 :126 调 AnnotationAwareOrderComparator.sort(conditions) ——戒律⼆在这⾥落地。

1.4 两个阶段:整章后半的地基// [framework] spring-context/src/main/java/org/springframework/context/annotation/ConfigurationCondition.java:41-59

enum ConfigurationPhase {

PARSE_CONFIGURATION,

REGISTER_BEAN

}

两个阶段的官⽅定义(原⽂):

PARSE_CONFIGURATION ( :44-47 ):在 @Configuration 类被解析时求值。不匹配 → 这个配置类根本不会被加进来。

REGISTER_BEAN ( :51-56 ):在注册普通 bean 时求值,不会阻⽌ @Configuration 类被加⼊。关键的⼀句在 :55-56 :

At the time that the condition is evaluated, all @Configuration classes will have been parsed.把这句话划下来。 它是 @ConditionalOnMissingBean 全部合法性的来源——只有等所有配置类都解析完、所有图纸都进了图纸库,"有没有这件器"才是⼀个有意义的问题。它同时也是那个时序陷阱的来源。⼀句话正反两⾯,第五节展开。

1.5 ⚠ 第⼀处该批评的地⽅:只有布尔值,没有理由Condition#matches 返回 boolean 。没了。

这意味着:Framework 层⾯上,⼀张图纸被否掉之后,世界上不存在任何地⽅记录着"它为什么被否掉"。 shouldSkip 返回 true,调⽤⽅ return ,图纸就此蒸发。

对 Framework ⾃⼰够⽤——它⾃带的唯⼀⼀个 Condition 是 ProfileCondition ( [framework] .../annotation/ProfileCondition.java:33 ,包私有), @Profile 就靠它。profile 没匹配上,你⾃⼰⼼⾥有数。

可 Boot 上来就往这个插槽⾥塞了⼀百多张⾃动配置图纸,每张挂三五个条件。这时候"没有理由"就是灾难:为什么我的 DataSource 没⽣效? 猜。

这就是⽂⻛圣经⾥点名的那条 Spring 通病——"⾃动配置的魔法难调试"——的制度性源头。Boot 后来不得不⾃⼰盖⼀层楼把理由捡回来(§3.1),但那是补救,不是设计。⼀个扩展点如果连"我为什么拒绝你"都表达不了,它的下游注定要为可观测性重新造⼀遍轮⼦。

⼆、核⼼谜题:检查⼀个不存在的类回到开场那个悖论。

2.1 官⽅原⽂// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClass.java:31-34A Class value can be safely specified on @Configuration classes as the annotationmetadata is parsed by using ASM before the class is loaded.⼀句话:在类被加载之前,注解元数据已经被 ASM 读出来了。

这正是 ch05 ⾥那条主线的第⼆次登场。当时我们说:类路径扫描全程不加载类,靠 ASM 以 SKIP_DEBUG | SKIP_CODE | SKIP_FRAMES 只读类头与注解表( [framework]spring-core/.../SimpleMetadataReader.java:38 、 :48 )。当时给的理由之⼀就是"加载可能直接炸"。现在,这条暗线在⾃动配置的世界⾥显出了它真正的分量——同⼀个⼿法,两处⽤;第⼀处是为了扫得快,第⼆处是为了根本不炸。

2.2 关键中的关键:Class 型注解值被就地降维成字符串证据在这⼗⾏:

// [framework] spring-core/src/main/java/org/springframework/core/type/classreading/MergedAnnotationReadingVisitor.java:69-75@Override

public void visit(String name, Object value) {
if (value instanceof Type type) {
value = type.getClassName();
}
this.attributes.put(name, value);
}

数组场景同理, ArrayVisitor.visit ( :171-177 )⾥是⼀模⼀样的三⾏。

@ConditionalOnClass(RedisTemplate.class) 在 class ⽂件⾥存的本来就只是⼀个 descriptor 字符串 Lorg/springframework/data/redis/core/RedisTemplate; 。

ASM 把它包成 org.springframework.asm.Type ,Spring ⽴刻把它拍平成 "org.springframework.data.redis.core.RedisTemplate" 。

从头到尾,没有任何⼀个类被加载过。 那个"类"在整条链路上的存在形式,就是⼀个 String 。

Boot 消费的时候也⽼⽼实实要字符串:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnClassCondition.java:118-125

MultiValueMap<String, @Nullable Object> attributes = metadata
.getAllAnnotationAttributes(annotationType.getName(), true); // true = classValuesAsString

...

addAll(candidates, attributes.get("value"));
addAll(candidates, attributes.get("name"));
🦴 ⻣灰级细节:看清楚 :124-125 这两⾏—— value 和 name 被 addAll 到同⼀个 List<String> ⾥。也就是说, @ConditionalOnClass(Foo.class) 和

@ConditionalOnClass(name = "com.x.Foo") 在运⾏时是完全等价的,都是字符串。两者的差别只存在于编译期:前者能被 IDE 重构、能被"查找引⽤"找到,仅此⽽已。

2.3 ⭐ 本基线的加料:读法换了,规矩没换到这⾥,⽹上所有讲这个话题的⽂章都会停在"Spring ⽤ ASM"。在本基线上,这个说法已经不完整了。

ch05 ⾥已经点破过:Framework 7 做了多版本 jar, [framework] spring-core/src/main/java24/ 下⾯有⼀整套 ClassFile* 实现,JDK 24 及以上改⽤ JDK ⾃带的java.lang.classfile ClassFile API 来读。

那么问题来了——换了⼀套读法,"Class 值降维成字符串"这条救命的规矩还在不在?

我去核了。在:

// [framework] spring-core/src/main/java24/org/springframework/core/type/classreading/ClassFileAnnotationDelegate.java:97-99

case AnnotationValue.OfClass classValue -> {
return ClassFileAnnotationMetadata.resolveTypeName(classValue.classSymbol());
}
这⾥调的 resolveTypeName(ClassDesc) 定义在隔壁⽂件( [framework] spring-

core/src/main/java24/org/springframework/core/type/classreading/ClassFileAnnotationMetadata.java:225 ),返回的是 String 。数组场景也照办——同⼀个

ClassFileAnnotationDelegate.java 的 resolveArrayElementType ⾥, :147 写着 case AnnotationValue.OfClass _ -> String.class; ,数组元素类型被直接声

明成 String.class ,压根没打算给你 Class[] 。

两套完全不同的字节码读取器,把同⼀条不成⽂的规矩原样搬了过去。 这不是巧合——这条规矩不是 ASM 的特性,是 Spring 的契约:凡从字节码读来的注解属性,Class ⼀律以名字形态存在。 换实现可以,破契约不⾏,因为整个 Boot 的⾃动配置都压在上⾯。

2.4 安全不在数据⾥,在消费姿势⾥现在来看最反直觉的⼀环。同⼀份 ASM 读来的 String[] ,如果消费端偏要 Class[] 呢?

// [framework] spring-core/src/main/java/org/springframework/core/annotation/TypeMappedAnnotation.java:461-473

else if (value instanceof String[] names && type == Class[].class) {
Class<?>[] classes = new Class<?>[names.length];
ClassLoader classLoader = getClassLoader();
for (int i = 0; i < names.length; i++) {
try {
classes[i] = ClassUtils.forName(names[i], classLoader);
}
catch (ClassNotFoundException | LinkageError ex) {
throw new TypeNotPresentException(names[i], ex);
}
}
value = classes;
}

就在这⾥炸。

这是本章最该带⾛的⼀句:"安全"不是数据的属性,是消费姿势的属性。 同⼀个 String[] ,你要 String[] 就永远安全,你要 Class[] 就当场TypeNotPresentException 。

所以 OnBeanCondition ⽤新⼀点的 MergedAnnotations API 时,会显式写上这个:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/OnBeanCondition.java:583

.collect(MergedAnnotationCollectors.toMultiValueMap(Adapt.CLASS_TO_STRING));

Adapt.CLASS_TO_STRING ⼲的事就是把"期望类型"从 Class / Class[] 改写成 String / String[] ,从⽽绕开上⾯那段。⼀个枚举常量,隔开了启动成功和启动崩溃。

2.5 🦴 但枚举是例外——两套读法都真的加载它Framework 内部对"哪些注解属性有危险"有⼀份名单:

// [framework] spring-core/src/main/java/org/springframework/core/annotation/AttributeMethods.java:84

this.canThrowTypeNotPresentException[i] = (type == Class.class || type == Class[].class || type.isEnum());

注意最后⼀项: type.isEnum() 。枚举型注解属性和 Class 型⼀样危险。

为什么?因为枚举值没法只⽤字符串表达——你得有那个枚举类才能 Enum.valueOf 。ASM 侧的 visitEnum 会 ClassUtils.forName 然后 throw newTypeNotPresentException ;ClassFile 侧⼀模⼀样:

// [framework] spring-core/src/main/java24/org/springframework/core/type/classreading/ClassFileAnnotationDelegate.java:125-133

private static Class<?> loadEnumClass(AnnotationValue.OfEnum enumValue, @Nullable ClassLoader classLoader) {
String className = ClassFileAnnotationMetadata.resolveTypeName(enumValue.classSymbol());
try {
return ClassUtils.forName(className, classLoader);
}
catch (ClassNotFoundException | LinkageError ex) {
throw new TypeNotPresentException(className, ex);
}
}
所以你会注意到⼀件事:条件注解⾥凡是枚举属性—— @ConditionalOnWebApplication(type = Type.SERVLET) 的 Type 、 @ConditionalOnMissingBean(search =

...) 的 SearchStrategy ——枚举类型本身永远是 Boot ⾃⼰包⾥的类,保证在。没有任何⼀个条件注解敢让你传第三⽅库⾥的枚举。

2.6 ⚠ 元注解为什么破功

ConditionalOnClass.java:71-75 ( value() 属性的 javadoc)的原话,请逐字读:

it is safe to specify classes here that may ultimately not be on the classpath, but only if this annotation is directly on the affectedcomponent and not if this annotation is used as a composed, meta-annotation. In order to use this annotation as a meta-annotation, only usethe name attribute.直接打在组件上,安全;当元注解⽤,不安全。

因为元注解的解析路径绕不开"反射加载那个组合注解类"。⼀旦⾛ java.lang.reflect 拿到真的 Annotation 实例,读它的 Class[] value() 就是 JVM 层⾯的属性解析——缺类就炸。Framework 为此专⻔做了⼀层试探性保护( AttributeMethods.canLoad(...) , :102-124 ,捕获 Throwable 后返回 false),但那只是让"读不到"变成"当作没有",救不了语义。

顺带记个数:这段警告在 ConditionalOnMissingBean.java ⾥出现了四次—— value 、 ignored 、 annotation 、 parameterizedContainer 四个属性各贴⼀遍。

仓库⾥的正⾯样板:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnCheckpointRestore.java:37

@ConditionalOnClass(name = "org.crac.Resource")

⽼⽼实实⽤ name ,因为 CRaC 那个库多半不在。

⽽这个看着像违规、其实合法:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingFilterBean.java:64

@ConditionalOnMissingBean(parameterizedContainer = FilterRegistrationBean.class)

规则的本质不是"元注解不许⽤ Class",⽽是"元注解上的 Class 必须保证可加载"。 FilterRegistrationBean 是 Boot ⾃⼰的类,永远在。

这⾥是本章第⼆处该批评的地⽅:这是⼀个必须靠写法约定才安全的机制。同⼀个注解,位置换⼀下语义就从"安全"翻成"崩溃",⽽编译器、IDE、静态检查全都不会提醒你。Boot团队能做的只有把警告在 javadoc ⾥贴四遍。⼀段⽂档需要重复四次,通常说明语⾔层⾯拦不住它。

2.7 第⼆、第三道保险第⼆道,真要探测存在性的时候:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/FilteringSpringBootCondition.java:115-121

protected static Class<?> resolve(String className, @Nullable ClassLoader classLoader)
throws ClassNotFoundException {
if (classLoader != null) {
return Class.forName(className, false, classLoader);
}
return Class.forName(className);
}

🦴 initialize = false 。即使类真的存在,也不执⾏它的静态初始化块。这避免了"我只是探⼀下有没有这个类,结果把⼈家的静态单例给建出来了"——观测⾏为不该改变被

观测对象,Spring 在这个五⾏的⽅法⾥守住了这条。

配套的 ClassNameFilter.isPresent 底层是 catch (Throwable ex) { return false; } ( :153 )——连 NoClassDefFoundError 、 LinkageError 都吞。必要:⽬

标类在、但它的某个⽗类/接⼝缺失时,抛的是 NoClassDefFoundError ⽽不是 ClassNotFoundException 。

第三道,万⼀还是漏了:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java:52-58

catch (NoClassDefFoundError ex) {
throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to "
+ ex.getMessage() + " not found. Make sure your own configuration does not rely on "

+ "that class. This can also happen if you are "

+ "@ComponentScanning a springframework package (e.g. if you "
+ "put a @ComponentScan in the default package by mistake)", ex);
}

⼀条能搜到答案的⼈话。这段⽂字本身就是 Boot 团队被这个坑折磨多年的化⽯。

2.8 ⚠ 暗礁: @Bean ⽅法上的 @ConditionalOnClass 是真的会炸前⾯说了⼀路"不会炸",现在说⼀处真会炸的。 ConditionalOnClass.java:36-39 的加粗 NOTE:

Note: Extra care must be taken when using @ConditionalOnClass on @Bean methods where typically the return type is the target of thecondition. Before the condition on the method applies, the JVM will have loaded the class and potentially processed method references whichwill fail if the class is not present.原因很朴素: @Bean ⽅法的返回类型是⽅法签名的⼀部分。要拿到那个 Method 对象,就得解析签名,就得加载返回类型。ASM 那套救不了你——它救的是"注解属性",救不了"⽅法签名"。

官⽅给的解法就写在同⼀段 javadoc 的代码样例⾥( :41-57 ):

@AutoConfiguration

public class MyAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(SomeService.class) //条件挂在类上,⾛字节码
public static class SomeServiceConfiguration {

@Bean@ConditionalOnMissingBean

public SomeService someService() {
return new SomeService();
}
}
}

✨ 爽点时刻:如果你翻过 Boot 的⾃动配置源码,⼀定⻅过"⼀个 @AutoConfiguration ⾥套着 N 个 static 内部 @Configuration "这种写法,并且⼤概率以为那是为了分

组、为了好看。

不是。那是为了不炸。

外层类先被解析、内层类的条件先在字节码层⾯判掉;条件不过,内层类整个不解析,那个危险的⽅法签名永远没机会被 JVM 碰到。回到 §1.1 的第三条规矩——"类上打了@Conditional ,整栋楼⼀起熄灯"——就是这套隔离术的语义依据。

三、Boot 那层楼:把布尔值升级成"带理由的判决"

3.1 SpringBootCondition :模板⽅法的教科书⽤法// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/SpringBootCondition.java:43-50@Override

public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String classOrMethodName = getClassOrMethodName(metadata);
try {
ConditionOutcome outcome = getMatchOutcome(context, metadata);
logOutcome(classOrMethodName, outcome);
recordEvaluation(context, classOrMethodName, outcome);
return outcome.isMatch();
}

...

}

看第 44 ⾏那个 final 。

Boot 在这⾥做了⼀件很硬的事:⼦类不许覆盖 matches 。所有 Boot 条件都被强制⾛完"求判决 → 记 TRACE ⽇志 → 记账 → 才降级成 boolean"这四步。⼦类只能实现抽象的getMatchOutcome ( :115 ),返回⼀个带理由的 ConditionOutcome 。

这是⼀处漂亮的设计:理由变成了免费的副产品。⼦类作者不需要"记得"去记账,语⾔机制替他记了。 ConditionEvaluationReport 之所以能做到零遗漏,制度保证就在这个final 上。

⚠ 但要注意 recordEvaluation ( :103 )有个前提: context.getBeanFactory() != null 才记。 ConditionContext ⾥ getBeanFactory() 和 getClassLoader()

这两个 getter 是 @Nullable 的( [framework] .../ConditionContext.java:48 、 :65 ),不是摆设——在纯 ClassPathScanningCandidateComponentProvider 这类没有 BeanFactory 的极端场景下,条件照跑,但报告是空的。

( ConditionOutcome / ConditionMessage 那套"英语造句 DSL"和最终的条件求值报告,是 ch41 的正菜,这⾥点到为⽌。)

3.2 @Order 表就是⼀篇成本论⽂Boot ⼀共 21 个 ConditionalOnXxx 注解( [boot] core/spring-boot-autoconfigure/.../condition/ 实测 46 个⽂件,含 package-info.java ),背后只有 12 个OnXxxCondition 实现类。它们的 @Order 排出来是这样:

Condition @Order 坐标(均在 [boot] core/spring-boot-autoconfigure/.../condition/ )

OnClassCondition HIGHEST_PRECEDENCE OnClassCondition.java:45OnWebApplicationCondition HIGHEST_PRECEDENCE + 20 OnWebApplicationCondition.java:47OnJavaCondition HIGHEST_PRECEDENCE + 20 OnJavaCondition.java:39OnResourceCondition HIGHEST_PRECEDENCE + 20 OnResourceCondition.java:40OnPropertyCondition HIGHEST_PRECEDENCE + 40 OnPropertyCondition.java:52OnExpressionCondition / OnJndiCondition / AnyNestedCondition LOWEST_PRECEDENCE - 20 各⾃ :40 / :40 / :57OnBeanCondition LOWEST_PRECEDENCE OnBeanCondition.java:88这张表读起来像⼀篇成本论⽂:

查类最便宜(只在类路径上找个⽂件名),排最前,⽽且最能短路。

中段是查环境(web 形态、Java 版本、资源、属性)——也便宜。

查 Bean 最贵(要遍历整个 BeanFactory、要解析泛型),排最后。

⽽且不只是"贵"。 OnBeanCondition 排最后还有⼀层语义上的必然——下⼀节就说这个。

配合 shouldSkip 的短路( [framework] .../ConditionEvaluator.java:100-101 ),结果是:最贵的那个条件,在绝⼤多数情况下根本不会被执⾏。便宜的先投票,贵的最后投,投不到最后就散会了。

四、看料的⼏种姿势4.1 @ConditionalOnProperty :三个默认值都容易记反先把真值表贴上(javadoc 原表, ConditionalOnProperty.java:39-69 ):

属性实际值 \ havingValue "" (默认) "true" "false" "foo"

"true" ✅ ✅ ❌ ❌"false" ❌ ❌ ✅ ❌"foo" ✅ ❌ ❌ ✅规则全在这五⾏⾥:

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/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);
}

三个回源核实过的默认值,每⼀个都常被记反:

  1. havingValue() default "" ( :135 )——语义不是"要求属性等于空串",是"只要不是 false 就算过"。
2. matchIfMissing() default false ( :142 )——属性压根不存在 = 不匹配。
3. ⽐较忽略⼤⼩写( equalsIgnoreCase )。 havingValue = "TRUE" 和 "true" ⼀回事。

⚠ 还有两条硬约束会让你启动直接失败: name 和 value 必须有⼀个,且不能同时有( OnPropertyCondition.java:157-162 两个 Assert.state ,报 The name and

value attributes of @%s are exclusive )。

⚠ 以及 javadoc :75-86 亲⼝承认的⼀条局限:这个注解不能可靠地⽤于集合属性。 @ConditionalOnProperty(prefix = "spring", name = "example.values") 在

spring.example.values 存在时匹配,但在 spring.example.values[0] 存在时不匹配。官⽅的建议是⼀句认输: It is better to use a custom condition forsuch cases.4.2 本基线新脸: @ConditionalOnBooleanProperty ( @since 3.5.0 )

这三个是家族⾥最年轻的成员,很多资料还没有: ConditionalOnBooleanProperty 、 ConditionalOnProperties 、 ConditionalOnBooleanProperties ,全部 @since3.5.0 。

⚠ 它和 @ConditionalOnProperty 的默认语义不⼀样,别混:

// [boot] core/spring-boot-autoconfigure/.../condition/ConditionalOnBooleanProperty.java:84

boolean havingValue() default true;

javadoc :31-32 原话: By default the properties must be present in the Environment and equal to true.

对照⼀下: spring.foo=bar 这条配置,会让 @ConditionalOnProperty("spring.foo") 匹配(因为"不是 false"),却会让

@ConditionalOnBooleanProperty("spring.foo") 不匹配(因为"不等于 true")。两个名字只差三个词的注解,默认⾏为相反。

另外 ConditionalOnProperty.java:98 现在标了 @Repeatable(ConditionalOnProperties.class) ,于是 OnPropertyCondition.getMatchOutcome ( :56-69 )要同

时处理四种注解形态,靠 :71-84 那四层 stream 拼起来。语义是 AND:只要⼀个 noMatch 就整体 noMatch,⽽且所有注解都会被求值不短路——为了报告完整,宁可多跑。

4.3 @ConditionalOnWebApplication :⼀个类⼲两件相反的事// [boot] core/spring-boot-autoconfigure/.../condition/OnWebApplicationCondition.java:92-102

public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean required = metadata.isAnnotated(ConditionalOnWebApplication.class.getName());
ConditionOutcome outcome = isWebApplication(context, metadata, required);
if (required && !outcome.isMatch()) {
return ConditionOutcome.noMatch(outcome.getConditionMessage());
}
if (!required && outcome.isMatch()) {
return ConditionOutcome.noMatch(outcome.getConditionMessage());
}
return ConditionOutcome.match(outcome.getConditionMessage());
}

🦴 @ConditionalOnWebApplication 和 @ConditionalOnNotWebApplication 共⽤同⼀个 Condition 类,靠第 93 ⾏那个 required 布尔把结论取反。

( OnWarDeploymentCondition ⽤同样的技巧同时服务 @ConditionalOnWarDeployment / @ConditionalOnNotWarDeployment 。)

两个探针常量是本基线的具体取值:

// [boot] core/spring-boot-autoconfigure/.../condition/OnWebApplicationCondition.java:50,52

private static final String SERVLET_WEB_APPLICATION_CLASS = "org.springframework.web.context.support.GenericWebApplicationContext";
private static final String REACTIVE_WEB_APPLICATION_CLASS = "org.springframework.web.reactive.HandlerResult";

🦴 ⽽ servlet 侧的探测顺序有个反直觉的第⼀步( :128-146 ):类查过之后,第⼆个信号不是任何类,⽽是" session 这个 scope 有没有被注册":

String[] scopes = context.getBeanFactory().getRegisteredScopeNames();
if (ObjectUtils.containsElement(scopes, "session")) {
return ConditionOutcome.match(message.foundExactly("'session' scope"));
}

为什么?因为条件求值发⽣得太早了——早到 ApplicationContext 的类型都还没完全定型。⽽ session scope 是 web 环境最早被注册进 BeanFactory 的痕迹之⼀。类 →scope → ConfigurableWebEnvironment → WebApplicationContext ,四重兜底,⼀层⽐⼀层晚,能在哪层认出来就在哪层认。

4.4 嵌套组合条件与那个必炸的坑AnyNestedCondition / AllNestedConditions / NoneNestedConditions (共同基类 AbstractNestedCondition , @since 1.5.22 )让你把⼏个条件按 OR / AND /NOR 组合起来。⽤法是把成员条件写成静态内部类:

// [boot] core/spring-boot-autoconfigure/.../condition/AnyNestedCondition.java:31-45(javadoc⾥的官⽅样例)

static class OnJndiOrProperty extends AnyNestedCondition {
OnJndiOrProperty() { super(ConfigurationPhase.PARSE_CONFIGURATION); }
@ConditionalOnJndi() static class OnJndi {}
@ConditionalOnProperty("something") static class OnProperty {}
}
🦴 成员条件的元数据也是读字节码读来的( MemberConditions ⾥ new SimpleMetadataReaderFactory(...) ),所以成员类上的 @ConditionalOnClass(Foo.class) 依

然安全——它⾛的是 @Conditional 本体解析,不是元注解合成。

⚠ 但这⾥埋着家族⾥最常⻅的⼀颗雷:阶段必须⼀致。

// [boot] core/spring-boot-autoconfigure/.../condition/AbstractNestedCondition.java:135-145

private void validateMemberCondition(Condition condition, ConfigurationPhase nestedPhase, String nestedClassName) {
if (nestedPhase == ConfigurationPhase.PARSE_CONFIGURATION
&& condition instanceof ConfigurationCondition configurationCondition) {
ConfigurationPhase memberPhase = configurationCondition.getConfigurationPhase();
if (memberPhase == ConfigurationPhase.REGISTER_BEAN) {
throw new IllegalStateException("Nested condition " + nestedClassName + " uses a configuration "
+ "phase that is inappropriate for " + condition.getClass());
}
}
}

外层声明成 PARSE_CONFIGURATION ,⾥⾯塞⼀个 @ConditionalOnBean (它是 REGISTER_BEAN 阶段的)——直接抛异常,启动失败。想混⽤,外层就得声明成REGISTER_BEAN 。

这不是刁难。它保护的正是下⼀节那件事。

五、⚠ 时序陷阱: @ConditionalOnMissingBean 只看"到⽬前为⽌"

这是整个家族⾥最容易出事的⼀个,也是本章的压轴。

5.1 官⽅⾃⼰把话说死了// [boot] core/spring-boot-autoconfigure/.../condition/ConditionalOnMissingBean.java:56-60The condition can only match the bean definitions that have been processed by theapplication context so far and, as such, it is strongly recommended to use thiscondition on auto-configuration classes only. If a candidate bean may be created byanother auto-configuration, make sure that the one using this condition runs after.关键词: so far 。

@ConditionalOnMissingBean 不是在问"这个坊⾥有没有这件器"。它在问的是——"截⽌到我被问的这⼀刻为⽌,图纸库⾥有没有登记过这件器?"

顺序决定成败。 同⼀份代码,把两个配置类的处理顺序调换,结论就翻转。

5.2 那它凭什么能⼯作?

因为 Boot ⽤了⼀套双保险的时序安排,两条都要成⽴才⾏:

保险⼀:⾃动配置被推到最后。

AutoConfigurationImportSelector 实现的是 DeferredImportSelector 。Framework 侧把这类 selector 收进 deferredImportSelectorHandler ( [framework]

.../ConfigurationClassParser.java:605 ),然后在 parse(...) 的最末⼀⾏才处理( :200 )。

于是:你⾃⼰的 @Configuration / @Component 先解析,图纸先⼊库;所有⾃动配置最后才轮到。 等⾃动配置开⼝问"有没有⼈已经定义过 DataSource "时,你的定义早就在库⾥了。这就是 ch38 那句"为什么⾃动配置总是最后才⽣效"在条件层⾯的兑现。

保险⼆: OnBeanCondition 的阶段是 REGISTER_BEAN 。

// [boot] core/spring-boot-autoconfigure/.../condition/OnBeanCondition.java:88-94

@Order(Ordered.LOWEST_PRECEDENCE)
class OnBeanCondition extends FilteringSpringBootCondition implements ConfigurationCondition {

@Override

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

回到 §1.4 划下来的那句: REGISTER_BEAN 阶段意味着"所有 @Configuration 类都已经解析完了"。这就是"看得⻅别⼈"的合法性来源。

也正因如此,§4.4 那个阶段校验才必须存在——把⼀个 REGISTER_BEAN 的条件硬塞进 PARSE_CONFIGURATION 阶段求值,它会在"⼤家都还没解析完"的时候去数 Bean,数出来的是个半成品答案。宁可启动失败,也不给你⼀个静默错误的结论。

5.3 那条注释:整个条件体系的哲学缩影// [boot] core/spring-boot-autoconfigure/.../condition/OnBeanCondition.java:690-698

private BeanType getReturnType(ConditionContext context, MethodMetadata metadata)
throws ClassNotFoundException, LinkageError {

// Safe to load at this point since we are in the REGISTER_BEAN phase

ClassLoader classLoader = context.getClassLoader();
ResolvableType returnType = getMethodReturnType(metadata, classLoader);
if (isParameterizedContainer(returnType.resolve())) {
returnType = returnType.getGeneric();
}
return new BeanType(returnType.toString(), returnType);
}

:692 那⾏注释—— Safe to load at this point since we are in the REGISTER_BEAN phase ——把前后两半章缝在了⼀起:

前半章拼了命不加载类;到了这⾥,它⼤⼤⽅⽅地反射加载了。因为阶段变了:到了 REGISTER_BEAN ,该在的类都该在了,不在的⾃动配置早在 PARSE_CONFIGURATION 就被@ConditionalOnClass 刷掉了。

加载类安全不安全,取决于你站在时间轴的哪⼀格。 这⼀条⽐任何技巧都更接近这套体系的本质。

顺带,即使这⼀步真失败了,它也不当场抛,⽽是包成 BeanTypeDeductionException 先存着,等到 validate 时发现"你什么类型信息都没给"才连着⼀起抛出来。

5.4 🦴 三条会让你"看不⻅"别⼈的过滤规则@ConditionalOnMissingBean 明明该看⻅的东⻄却没看⻅,通常是撞上了这三条之⼀:

(a) allowEagerInit = false —— FactoryBean 的暗礁。

// [boot] core/spring-boot-autoconfigure/.../condition/OnBeanCondition.java:334

result = putAll(result, beanFactory.getBeanNamesForType(type.resolvableType(), true, false), beanFactory);
// includeNonSingletons ↑ ↑ allowEagerInit = false

第三个参数是 false :绝不为了搞清楚某个 FactoryBean 会产出什么类型,就把它实例化(否则就违反了 §1.2 的戒律⼀)。代价是:如果某个 FactoryBean 的产出类型在图纸层⾯推不出来, @ConditionalOnMissingBean 看不⻅它产出的那件器,于是⾃动配置照样⽣效——最后你的坊⾥出现了两件同类型的器。

这就是官⽅⽂档反复叮嘱"在 @Bean ⽅法上提供尽可能多的类型信息"的深层原因:条件求值只能依赖⽅法签名上写着的东⻄。你写 public Object dataSource() ,就别指望条件能认出它。

(b) ⾮ autowire 候选 / ⾮ default 候选的 Bean 被直接⽆视。

// [boot] core/spring-boot-autoconfigure/.../condition/OnBeanCondition.java:285

if (definition == null || (definition.isAutowireCandidate() && isDefaultCandidate(definition))) {
return true;
}
javadoc 也明写了: Beans that are not autowire candidates or that are not default candidates are ignored. 你⽤ @Bean(autowireCandidate = false) 定

义的那件器,在条件眼⾥等于不存在。

(c) SearchStrategy 默认是 ALL ,会往上翻⽗上下⽂。

ConditionalOnMissingBean.java:153 : SearchStrategy search() default SearchStrategy.ALL; ——默认整条上下⽂层级都看。所以在"主上下⽂ + 管理上下⽂"这种

⽗⼦结构⾥,你会看到 Boot ⾃⼰在某些地⽅显式写 search = SearchStrategy.CURRENT ,就是怕被⽗上下⽂的同名 Bean 误伤。

5.5 ⚠ 最后⼀条,也是最容易犯的:别在⾃⼰的 @Configuration 上⽤它官⽅参考⽂档( [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc )连着三条警告,其中两条抄在这⾥:

You need to be very careful about the order in which bean definitions are added, as these conditions are evaluated based on what has beenprocessed so far.@ConditionalOnBean and @ConditionalOnMissingBean do not prevent @Configuration classes from being created. The only difference betweenusing these conditions at the class level and marking each contained @Bean method with the annotation is that the former prevents

registration of the @Configuration class as a bean if the condition does not match.第⼆条很多⼈没读懂:这两个条件打在类上,并不能阻⽌那个 @Configuration 类被"创建"(它已经被解析、⾥⾯的 @Bean ⽅法逻辑仍会按各⾃条件⾛);类级和⽅法级唯⼀的差别,是前者会阻⽌把配置类本身注册成⼀个 bean。

⽽第⼀条的实战推论只有⼀句: @ConditionalOnMissingBean 是给⾃动配置写的,不是给你的业务配置类写的。

因为你的配置类被解析的时候,⾃动配置⼀张都还没轮到——你去问"有没有⼈已经定义了 RedisTemplate ",答案永远是"没有"。你以为你在写"⽤户没配我才配",实际写成了"我总是配"。

这⾥是本章第三处批评,也是分量最重的⼀处: @ConditionalOnMissingBean 是⼀个正确性依赖于求值顺序的 API。⽽这个顺序,由 @AutoConfigureBefore /@AutoConfigureAfter / @AutoConfigureOrder 在⼀个你看不⻅的排序器⾥决定。同⼀个注解,写在 A 类⾥⽣效、写在 B 类⾥失效,源码⼀模⼀样。这是"Spring 的⼀个⾏为要跨注解、⾃动配置、属性⽂件、条件求值好⼏处才拼得出来"这条批评最尖锐的实例——它不报错、不警告,只是给你⼀个不同的结论。

六、两次机会:还有⼀条你可能不知道的快速通道最后补⼀条很多⼈不知道的:⾃动配置的条件,其实求值了两遍。

[boot] core/spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories ⾥注册着三个"导⼊过滤器":

org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\

org.springframework.boot.autoconfigure.condition.OnBeanCondition,\org.springframework.boot.autoconfigure.condition.OnClassCondition,\org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition只有三个,⽽且都继承⾃ FilteringSpringBootCondition ——⼀个类同时是 Condition 和 AutoConfigurationImportFilter ,⼀套判定逻辑,两个⼊⼝。

这条快速通道在配置类还没开始解析的时候,就先拿⼀份编译期⽣成的元数据( META-INF/spring-autoconfigure-metadata.properties ,由 spring-boot-autoconfigure-processor 这个注解处理器产出)把明显不匹配的⾃动配置整批刷掉,省下解析成本。

🦴 两个细节值得记:

其⼀,注解处理器会给类名排序,⾮ Spring 的类排在前⾯( [boot] core/spring-boot-autoconfigure-processor/.../AutoConfigureAnnotationProcessor.java:277-

279 ,⽐较器是 Comparator.comparing(this::isSpringClass).thenComparing(String.CASE_INSENSITIVE_ORDER) )。因为第三⽅类更可能缺失,先查它更容易短路。⼀

个纯粹为了启动速度的微优化,被下沉到了编译期。

其⼆,快速通道允许⾃⼰出错:

// [boot] core/spring-boot-autoconfigure/.../condition/OnClassCondition.java:236-238

catch (Exception ex) {

// We'll get another chance later

}

吞掉异常、当作"没结论"。因为正规的 @Conditional 求值后⾯还会再来⼀次——有两次机会,所以第⼀次可以放⼼地激进。

顺带还有⼀处克制得可爱的优化: OnClassCondition 在多核机器上会只开⼀个额外线程对半分⼯( :48-56 ),注释直⾔ Using a single additional thread seems tooffer the best performance. More threads make things worse. 类加载本身在 JVM 内部有锁竞争,开更多线程只会更慢。有实测⽀撑的克制,⽐没根据的并⾏化值钱。

🎯 三句带⾛1. @ConditionalOnClass 之所以不炸,是因为注解⾥的 Class 字⾯量从头到尾只以字符串形态存在( [framework] MergedAnnotationReadingVisitor.java:71-73 ,JDK 24+ 的 ClassFile 读法在 spring-core/src/main/java24/.../ClassFileAnnotationDelegate.java:97-99 保持同⼀契约);要 String[] 就安全,要Class[] 就 TypeNotPresentException ( [framework] TypeMappedAnnotation.java:461-473 )。两个例外:当元注解⽤时必须写 name , @Bean ⽅法的返回类型救不了(要⽤嵌套 @Configuration 隔离)。

  1. @ConditionalOnMissingBean 只能看⻅"到⽬前为⽌已处理的 BeanDefinition"——它靠"⾃动配置是 DeferredImportSelector ,最后才处理"+" OnBeanCondition是 REGISTER_BEAN 阶段"这两件事才成⽴。只在⾃动配置类上⽤它;写在⾃⼰的 @Configuration 上等于永远匹配。
  1. 默认值回源核实: @ConditionalOnProperty 的 matchIfMissing 默认 false 、 havingValue 默认 "" 意为"只要不是 false "、⽐较忽略⼤⼩写;

@ConditionalOnBooleanProperty ( @since 3.5.0 )默认要求"存在且等于 true ",与前者不同; @ConditionalOnMissingBean 的 search 默认 ALL (会往上翻⽗上下⽂)。

承上启下到这⾥,"看料下单"的机制全套拆完了:怎么看料(读字节码⽽不加载类)、什么时候看(两个阶段)、按什么顺序看( @Order 那篇成本论⽂)、以及看晚了会怎样(时序陷阱)。

但有⼀件事我们⼀直绕着⾛:料,是谁送来的?

@ConditionalOnClass(RedisTemplate.class) ⾥的那个类,凭什么会出现在类路径上?你并没有⼀条条去写 spring-data-redis 、 lettuce-core 、 commons-pool2 的

坐标和版本——你只写了⼀⾏ spring-boot-starter-data-redis 。

下⼀章拆开这个"配好的料包"。你会发现最反直觉的⼀点:⼀个 starter ⾥头,往往⼀件成品也没有——它只有⼀张清单。

⼀个不含任何代码的 jar,凭什么是整个 Spring Boot 体验的⻔⾯?