本文介绍了将@Profile批注与属性占位符值一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在春季为任何组件定义轮廓时,我们将其声明为@Profile(value="Prod").但是我想从属性文件中给出该值.是否有可能?如果是,怎么办?

When we define profile for any component in spring, we declare it as@Profile(value="Prod"). But i want to give that value from properties file.Is it possible? If yes, how?

推荐答案

通过Spring的源代码,我得出的结论是,您要问的是不可能的.为了清楚起见,Spring无法在@Profile中评估${property}.

Going through the source code of Spring, I have arrived to the conclusion that what you are asking is not possible. To make this clear, it is not possible to have Spring evaluate ${property} inside @Profile.

具体看看ProfileCondition,它检查配置文件是否处于活动状态.

Specifically take a look at ProfileCondition which checks whether or not the profile is active.

class ProfileCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        if (context.getEnvironment() != null) {
            MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
            if (attrs != null) {
                for (Object value : attrs.get("value")) {
                    if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
                        return true;
                    }
                }
                return false;
            }
        }
        return true;
    }

}

肉是context.getEnvironment().acceptsProfiles(((String[]) value)).

现在,如果检查acceptsProfiles所在的AbstractEnvironment的来源,您会发现控件到达

Now if you check the source of AbstractEnvironment where acceptsProfiles resides, you will find that the control reaches

protected boolean isProfileActive(String profile) {
    validateProfile(profile);
    return doGetActiveProfiles().contains(profile) ||
            (doGetActiveProfiles().isEmpty() && doGetDefaultProfiles().contains(profile));
}

它不尝试求值表达式,而是按原样使用String(还要注意,isProfileActive之前的任何地方都不是要求值的String表达式)

which does not attempt to evaluate the expression, but takes the String verbatim (also note that nowhere before isProfileActive is the String expression being evaluated either)

您可以找到我上面提到的代码此处此处.

You can find the code I have mentioned above here and here.

请注意,我不确定为什么需要使用动态配置文件名称.

One another note, I am not sure why you would need to have a dynamic profile name.

这篇关于将@Profile批注与属性占位符值一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:26