本文基于
Spring 5.1.7.release
SpringBoot 2.1.5.release
Spring 中的 @Condition 能非常方便帮助我们条件化的注册 bean。这里我不做 @Conditional 相关注解的介绍。这里介绍些下 Condition 的调用过程和一些注意事项。
今天再看事务自动配置类 TransactionAutoConfiguration
时发现静态内部类 EnableTransactionManagementConfiguration
的注册并不是我预期的样子, TransactionAutoConfiguration
的代码如下:
package org.springframework.boot.autoconfigure.transaction;
...
...
/**
* {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration
* Auto-configuration} for Spring transaction.
*
* @author Stephane Nicoll
* @since 1.3.0
*/
@Configuration
@ConditionalOnClass(PlatformTransactionManager.class)
@AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
Neo4jDataAutoConfiguration.class })
@EnableConfigurationProperties(TransactionProperties.class)
public class TransactionAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public TransactionManagerCustomizers platformTransactionManagerCustomizers(
ObjectProvider> customizers) {
return new TransactionManagerCustomizers(
customizers.orderedStream().collect(Collectors.toList()));
}
@Configuration
@ConditionalOnSingleCandidate(PlatformTransactionManager.class)
public static class TransactionTemplateConfiguration {
private final PlatformTransactionManager transactionManager;
public TransactionTemplateConfiguration(
PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Bean
@ConditionalOnMissingBean
public TransactionTemplate transactionTemplate() {
return new TransactionTemplate(this.transactionManager);
}
}
@Configuration
@ConditionalOnBean(PlatformTransactionManager.class)
@ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)
public static class EnableTransactionManagementConfiguration {
@Configuration
@EnableTransactionManagement(proxyTargetClass = false)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class",
havingValue = "false", matchIfMissing = false)
public static class JdkDynamicAutoProxyConfiguration {
}
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class",
havingValue = "true", matchIfMissing = true)
public static class CglibAutoProxyConfiguration {
}
}
}
可以看到 EnableTransactionManagementConfiguration
使用了 :
- @ConditionalOnBean(PlatformTransactionManager.class)
- @ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)
起初我认为如果 BeanFactory 中有 PlatformTransactionManager 且没有 AbstractTransactionManagementConfiguration 才会进入内部进行内部的初始化(也就是说 @EnableTransactionManagement 注解不会起作用,也就是说不会进入 TransactionManagementConfigurationSelector ),但是当我把 PlatformTransactionManager 的 bean 定义去除后,发现还是会进入到 TransactionManagementConfigurationSelector,这使我很疑惑。经过一系列 debug 后终于找到了原因。
Condition 原理
首先所有的 Configuration 都会被 ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry
处理,之后会被 ConfigurationClassParser#parse(Set
解析。在解析时会调用 ConditionEvaluator#shouldSkip
判断是否需要把目标解析为 ConfigurationClass,解析时的判断源码如下:
1. ConfigurationClassParser#parse -> ConfigurationClassParser#processConfigurationClass
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);
this.configurationClasses.put(configClass, configClass);
}
shouldSkip 判断是否跳过 configClass 的解析,注意这里使用的是ConfigurationPhase.PARSE_CONFIGURATION,这也是为什么我之前的以为是错误的原因。
ConfigurationPhase.PARSE_CONFIGURATION 表示 Condition 只有在解析阶段才起作用,也就是说 Condition 不是 ConfigurationCondition 的实现或者阶段不匹配都不会跳过
2. shouldSkip
/**
* false: 不跳过,true:跳过
*/
public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationP
// metadata == null 或 没有注解 @Conditional 相关的类,直接返回 false
if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
return false;
}
// 如果 phase (阶段为空),判断类上是否有 @Configuration, @Component,@ComponentScan,@Import,@ImportResource
// 或方法上有 @Bean 注解,如果有就使用 ConfigurationPhase.PARSE_CONFIGURATION)
if (phase == null) {
if (metadata instanceof AnnotationMetadata &&
ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metada
return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
}
return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
}
List conditions = new ArrayList<>();
// 获取 @Conditional 注解对应得 Condtion 放入 conditions,这里使用了反射
for (String[] conditionClasses : getConditionClasses(metadata)) {
for (String conditionClass : conditionClasses) {
Condition condition = getCondition(conditionClass, this.context.getClassLoader()
conditions.add(condition);
}
}
// 排序
AnnotationAwareOrderComparator.sort(conditions);
// 遍历 Condition 判断是否应该跳过
for (Condition condition : conditions) {
ConfigurationPhase requiredPhase = null;
// 如果 Condition 实现了 ConfigurationCondition 则获取该 Condition 得阶段
if (condition instanceof ConfigurationCondition) {
requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
}
// 如果 (requiredPhase == null || 阶段匹配 ) && matches 返回 false 就返回 true
// 如果 requiredPhase != null && 阶段不匹配 直接返回 false
if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
return true;
}
}
return false;
}
看到这我们会看
- @ConditionalOnBean(PlatformTransactionManager.class)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnBean {
- @ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnMissingBean {
可以看到这两个 @Conditonal 都是用得是 OnBeanCondition 来处理。翻看源码发现 OnBeanCondition 实现了 ConfigurationCondition,它的处理阶段是 ConfigurationPhase.REGISTER_BEAN(也就是注册阶段)。
看到这,相信大家对整个得 Condition 处理逻辑有了大概得了解,也明白为什么我起初得错误是错误的吧。
Conclusion
在使用 @Condtional 相关注解时需要注意对应的 Condition 起作用的阶段,防止使用错误。