SpringBoot之@ConditionalOnProperty注解

在平时业务中,我们需要在配置文件中配置某个属性来决定是否需要将某些类进行注入,让Spring进行管理,而@ConditionalOnProperty能够实现该功能。
@ConditionalOnProperty:根据属性值来控制类或某个方法是否需要加载。它既可以放在类上也可以放在方法上。

1、SpringBoot实现

1.1 设置配置属性

在applicatio.properties或application.yml配置isload_bean = true;

#配置是否加载类
is_load_bean: true</pre>

1.2 编写加载类

编写加载类,使用@Component进行注解,为了便于区分,我们将@ConditionalOnProperty放在方法上。

 * @author: jiangjs
 * @description: 使用@ConditionalOnProperty
 * @date: 2023/4/24 10:20
 **/
@Component
@Slf4j
public class UseConditionalOnProperty {

    @Value("${is_load_bean}")
    private String isLoadBean;

    @Bean
    @ConditionalOnProperty(value = "is_load_bean",havingValue = "true",matchIfMissing = true)
    public void loadBean(){
        log.info("是否加载当前类");
    }

    @Bean
    public void compareLoadBean(){
        log.info("加载bean属性:" + isLoadBean);
    }
}

启动项目时输出打印的日志。如图:



将配置文件的数据信息改成false,则不会打印出结果。


image.png

2、ConditionalOnProperty属性与源码

2.1 属性

查看@ConditionalOnProperty源码可以看到该注解定义了几个属性。

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {

    /**
     * name别名,数组类型,获取对应property名称的值,与name不能同时使用
     */
    String[] value() default {};

    /**
     * 属性前缀,未指定时,自动以点"."结束,有效前缀由一个或多个词用点"."连接。
     * 如:spring.datasource
     */
    String prefix() default "";

    /**
     * 属性名称,配置属性完整名称或部分名称,可与prefix组合使用,不能与value同时使用
     */
    String[] name() default {};

    /**
     * 可与name组合使用,比较获取到的属性值与havingValue的值是否相同,相同才加载配置
     */
    String havingValue() default "";

    /**
     * 缺少该配置属性时是否加载,默认为false。如果为true,没有该配置属性时也会正常加载;反之则不会生效
     */
    boolean matchIfMissing() default false;

}

1、属性name与value不能同时使用,我们在看源码时会发现做了判断
2、value相当于是name的别名一样,源码中会取value或name赋值给names的属性
3、havingValue:设置的属性值,当配置文件中配置的属性值与havingValue的值相同时才加载该类
4、matchIfMissing:当配置文件中缺少该配置时,是否需要加载类,true:表示加载,false:不加载

2.2 源码

查看OnPropertyCondition类中国的getMatchOutcome()方法:

@Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //获取所有注解ConditionalOnProperty下的所有属性match,message
        List<AnnotationAttributes> allAnnotationAttributes = annotationAttributesFromMultiValueMap(
                metadata.getAllAnnotationAttributes(ConditionalOnProperty.class.getName()));
        List<ConditionMessage> noMatch = new ArrayList<>();
        List<ConditionMessage> match = new ArrayList<>();
        //遍历注解中的属性
        for (AnnotationAttributes annotationAttributes : allAnnotationAttributes) {
            //创建判定的结果,ConditionOutcome只有两个属性,
            ConditionOutcome outcome = determineOutcome(annotationAttributes, context.getEnvironment());
            (outcome.isMatch() ? match : noMatch).add(outcome.getConditionMessage());
        }
        if (!noMatch.isEmpty()) {
            //如果有属性没有匹配,则返回
            return ConditionOutcome.noMatch(ConditionMessage.of(noMatch));
        }
        return ConditionOutcome.match(ConditionMessage.of(match));
    }

在上述源码中determineOutcome()是关键方法,我们来看看:

private ConditionOutcome determineOutcome(AnnotationAttributes annotationAttributes, PropertyResolver resolver) {
    //初始化
    Spec spec = new Spec(annotationAttributes);
    List<String> missingProperties = new ArrayList<>();
    List<String> nonMatchingProperties = new ArrayList<>();
    //收集属性,将结果赋值给missingProperties,nonMatchingProperties
    spec.collectProperties(resolver, missingProperties, nonMatchingProperties);
    if (!missingProperties.isEmpty()) {
        //missingProperties属性不为空,说明设置matchIfMissing的是false,则不加载类
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
                .didNotFind("property", "properties").items(Style.QUOTE, missingProperties));
    }
    if (!nonMatchingProperties.isEmpty()) {
        //nonMatchingProperties属性不为空,则设置的属性值与havingValue值不匹配,则不加载类
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnProperty.class, spec)
                .found("different value in property", "different value in properties")
                .items(Style.QUOTE, nonMatchingProperties));
    }
    return ConditionOutcome
            .match(ConditionMessage.forCondition(ConditionalOnProperty.class, spec).because("matched"));
}

Spec是OnPropertyCondition的一个静态内部类,初始化@ConditionalOnProperty中的属性。

private static class Spec {

        private final String prefix;

        private final String havingValue;

        private final String[] names;

        private final boolean matchIfMissing;
        //初始化,给各属性赋值
        Spec(AnnotationAttributes annotationAttributes) {
            String prefix = annotationAttributes.getString("prefix").trim();
            if (StringUtils.hasText(prefix) && !prefix.endsWith(".")) {
                prefix = prefix + ".";
            }
            this.prefix = prefix;
            this.havingValue = annotationAttributes.getString("havingValue");
            this.names = getNames(annotationAttributes);
            this.matchIfMissing = annotationAttributes.getBoolean("matchIfMissing");
        }

        //处理name与value
        private String[] getNames(Map<String, Object> annotationAttributes) {
            String[] value = (String[]) annotationAttributes.get("value");
            String[] name = (String[]) annotationAttributes.get("name");
            //限制了value或name必须指定
            Assert.state(value.length > 0 || name.length > 0,
                    "The name or value attribute of @ConditionalOnProperty must be specified");
            //value和name只能有一个存在,不能同时使用
            Assert.state(value.length == 0 || name.length == 0,
                    "The name and value attributes of @ConditionalOnProperty are exclusive");
            return (value.length > 0) ? value : name;
        }

        private void collectProperties(PropertyResolver resolver, List<String> missing, List<String> nonMatching) {
            //遍历names,即value或name的值
            for (String name : this.names) {
                //前缀 + name,获取配置文件中key
                String key = this.prefix + name;
                //验证配置属性中包含key
                if (resolver.containsProperty(key)) {
                    //如包含,则获取key对应的值,与havingValue的值进行匹配
                    if (!isMatch(resolver.getProperty(key), this.havingValue)) {
                        //不匹配则添加到nonMatching
                        nonMatching.add(name);
                    }
                }
                else {
                    //验证配置属性中没有包含key,判断是否配置了matchIfMissing属性
                    if (!this.matchIfMissing) {
                        //该属性不为true则添加到missing中
                        missing.add(name);
                    }
                }
            }
        }

        private boolean isMatch(String value, String requiredValue) {
            //验证requiredValue是否有值
            if (StringUtils.hasLength(requiredValue)) {
                //有值,则进行比较,不区分大小写
                return requiredValue.equalsIgnoreCase(value);
            }
            //没有值,则验证value是否等于false
            //这也是为什么name, value不配置值的情况下, 类依然会被加载的原因
            return !"false".equalsIgnoreCase(value);
        }

        @Override
        public String toString() {
            StringBuilder result = new StringBuilder();
            result.append("(");
            result.append(this.prefix);
            if (this.names.length == 1) {
                result.append(this.names[0]);
            }
            else {
                result.append("[");
                result.append(StringUtils.arrayToCommaDelimitedString(this.names));
                result.append("]");
            }
            if (StringUtils.hasLength(this.havingValue)) {
                result.append("=").append(this.havingValue);
            }
            result.append(")");
            return result.toString();
        }

    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容