将@Profile注释与属性占位符值一起使用

Mas*_*ode 5 spring spring-boot

当我们在spring中定义任何组件的配置文件时,我们将其声明为 @Profile(value="Prod").但我想从属性文件中提供该值.可能吗?如果有,怎么样?

geo*_*and 6

通过查看Spring的源代码,我得出的结论是,你所要求的是不可能的。为了明确这一点,不可能让 Spring${property}在内部进行评估@Profile

具体看一下ProfileCondition它检查配置文件是否处于活动状态。

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

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

AbstractEnvironment现在如果你检查where驻留的来源acceptsProfiles,你会发现控件达到了

protected boolean isProfileActive(String profile) {
    validateProfile(profile);
    return doGetActiveProfiles().contains(profile) ||
            (doGetActiveProfiles().isEmpty() && doGetDefaultProfiles().contains(profile));
}
Run Code Online (Sandbox Code Playgroud)

它不会尝试计算表达式,而是逐字获取字符串(另请注意,之前也没有isProfileActive对字符串表达式进行计算)

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


另请注意,我不确定为什么您需要一个动态配置文件名称。


Ste*_*eve 5

您似乎试图滥用@Profile注释.使用配置文件启用功能.不是说Bean在特定环境中是活动的.

实现更接近我认为您正在寻找的东西的方法是使用特定于您的环境的属性文件,这些属性文件定义应在其中激活的配置文件.这样,您就可以使用以下参数启动应用:

--spring.profiles.active=prd
Run Code Online (Sandbox Code Playgroud)

然后Spring Boot将尝试加载application-prd.properties,您可以在其中激活特定于环境的配置文件:

spring.profiles.active=sqlserver,activedirectory,exchangeemail
Run Code Online (Sandbox Code Playgroud)

这样,您的bean只有在需要它们提供的功能时才会被激活.