根据条件加载 bean:即 @ConditionalOnXxx 的解析

(version: SpringBoot 2.2.2.RELEASE)

加载 @Configration 类,或者 @Configuration 类里面的 beanMethod 时,通常会用到条件加载,即:@CondtionalOnXxx

1. org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader#loadBeanDefinitionsForConfigurationClass()
    1.1 org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.TrackedConditionEvaluator#shouldSkip()

 

具体的实现代码如下:
org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.TrackedConditionEvaluator#shouldSkip()

public boolean shouldSkip(ConfigurationClass configClass) {
    Boolean skip = this.skipped.get(configClass);
    if (skip == null) {
        if (configClass.isImported()) {
            boolean allSkipped = true;
            for (ConfigurationClass importedBy : configClass.getImportedBy()) {
                if (!shouldSkip(importedBy)) {
                    allSkipped = false;
                    break;
                }
            }
            if (allSkipped) {
                // The config classes that imported this one were all skipped, therefore we are skipped...
                skip = true;
            }
        }
        if (skip == null) {
            // 通过表达式来判断是否要 skip:即 @ConditionalOnBean、@ConditionOnClass、@ConditionalOnMissingClass、@ConditionalOnExpression 等的处理
            skip = conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN);
        }
        this.skipped.put(configClass, skip);
    }
    return skip;
}

 

posted on 2020-03-07 00:05  快鸟  阅读(2607)  评论(0编辑  收藏  举报