Java Spring @ConditionalOnProperty 具有值 = "value1" 或 "value2"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51257432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:02:57  来源:igfitidea点击:

Spring @ConditionalOnProperty havingValue = "value1" or "value2"

javaspringspring-bootjavabeans

提问by MLS

I am looking for configurationOnPropertyusage where I can specify to consider more than one value as shown below

我正在寻找configurationOnProperty可以指定考虑多个值的用法,如下所示

Eg: @ConditionalOnProperty(value = "test.configname", havingValue = "value1" or "value2")

例如: @ConditionalOnProperty(value = "test.configname", havingValue = "value1" or "value2")

OR

或者

I would like to know if it is possible to specify confiugrationOnPropertywith condition of havingValue != "value3"

我想知道是否可以指定confiugrationOnProperty条件为havingValue != "value3"

Eg: @ConditionalOnProperty(value = "test.configname", havingValue != "value3")

例如: @ConditionalOnProperty(value = "test.configname", havingValue != "value3")

Please let me know if there is a way to achieve any one of the above in spring bootconfiguration.

请让我知道是否有办法在spring boot配置中实现上述任何一项。

采纳答案by Andy Wilkinson

Spring Boot provides AnyNestedConditionfor created a condition that will match when any nested condition matches. It also provides AllNestedConditionsand NoneNestedConditionsfor matching when all nested conditions or no nested conditions match respectively.

Spring Boot 提供AnyNestedCondition了创建的条件,该条件将在任何嵌套条件匹配时进行匹配。当所有嵌套条件或没有嵌套条件分别匹配时,它还提供AllNestedConditionsNoneNestedConditions用于匹配。

For your specific case where you want to match a value of value1or value2you would create an AnyNestedConditionlike this:

对于您想要匹配值的特定情况,value1或者value2您将创建AnyNestedCondition这样的:

class ConfigNameCondition extends AnyNestedCondition {

    public ConfigNameCondition() {
        super(ConfigurationPhase.PARSE_CONFIGURATION);
    }

    @ConditionalOnProperty(name = "test.configname", value = "value1")
    static class Value1Condition {

    }

    @ConditionalOnProperty(name = "test.configname", value = "value2")
    static class Value2Condition {

    }

}

And then use it with @Conditional, like this for example:

然后将其与 一起使用@Conditional,例如:

@Bean
@Conditional(ConfigNameCondition.class)
public SomeBean someBean() {
    return new SomeBean();
}

As shown in the javadoc for the nested condition annotations (linked to above) the nested conditions can be of any type. There's no need for them to all be of the same type as they are in this particular case.

如嵌套条件注释的 javadoc 所示(链接到上面),嵌套条件可以是任何类型。没有必要让它们都与在这种特殊情况下的类型相同。

回答by Yogen Rai

You can use an array of conditional value as:

您可以将条件值数组用作:

@Configuration
public class MyConfigClass {

    @Bean
    @ConditionalOnProperty(prefix="test.configname", value = { "value1", "value2" })
    public MyBean myBean() {
        return new MyBean();
    }
}

This will create bean if property test.configname.value1or test.configname.value2exists, and value not false.

如果属性test.configname.value1test.configname.value2存在,这将创建 bean ,并且 value 不是 false。

The Spring Boot Documenthas proper description for this.

春季启动文件有这个正确描述。

回答by Alien

The annotations @ConditionalOnPropertyand @ConditionalOnExpressionboth do NOT have the java.lang.annotation.Repeatableannotation so you would not be able to just add multiple annotations for checking multiple properties.

注释@ConditionalOnProperty@ConditionalOnExpression两者都没有java.lang.annotation.Repeatable注释,因此您无法仅添加多个注释来检查多个属性。

The following syntax has been tested and works:

以下语法已经过测试并有效:

Solution for Two Properties

两个属性的解决方案

@ConditionalOnExpression("${properties.first.property.enable:true} && ${properties.second.property.startServer:false}")

Note the following:

请注意以下事项:

  • You need to using colon notation to indicate the default value of the property in the expression language statement
  • Each property is in a separate expression language block ${}
  • The && operator is used outside of the SpEL blocks
  • 表达式语言语句中需要使用冒号表示属性的默认值
  • 每个属性都在一个单独的表达式语言块 ${}
  • && 运算符在 SpEL 块之外使用

It allows for multiple properties that have differing values and can extend to multiple properties.

它允许具有不同值的多个属性并且可以扩展到多个属性。

If you want to check more then 2 values and still maintain readability, you can use the concatenation operator between different conditions you are evaluating:

如果要检查多于 2 个值并仍保持可读性,可以在要评估的不同条件之间使用连接运算符:

Solution for more then 2 properties

超过 2 个属性的解决方案

@ConditionalOnExpression("${properties.first.property.enable:true} " +
        "&& ${properties.second.property.enable:true} " +
        "&& ${properties.third.property.enable:true}")

The drawback is that you cannot use a matchIfMissing argument as you would be able to when using the @ConditionalOnPropertyannotation so you will have to ensure that the properties are present in the .propertiesor YAMLfiles for all your profiles/environments or just rely on the default value

缺点是您不能像使用注释一样使用 matchIfMissing 参数,@ConditionalOnProperty因此您必须确保所有配置文件/环境的.propertiesYAML文件中都存在这些属性,或者仅依赖默认值价值

Taken from here Spring Boot SpEL ConditionalOnExpression check multiple properties

取自此处Spring Boot SpEL ConditionalOnExpression 检查多个属性

回答by Mehraj Malik

I am looking for configurationOnPropertyusage where I can specify to consider more than one value

我正在寻找configurationOnProperty可以指定考虑多个值的用法

You can use Condition interfaceof Spring 4.0.

您可以使用条件接口Spring 4.0

This interface has a method matches(...)which you can use.

这个接口有一个matches(...)你可以使用的方法。

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class TestCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String testValue = (context.getEnvironment().getProperty("test.configname");
        return "value1".equalsIgnoreCase("testValue") || "value2".equalsIgnoreCase("testValue");
    }

}

And then use TestConditioninside your @Configurationlike below :

然后TestCondition在你@Configuration喜欢的下面使用:

@Configuration
public class TestConfig {

      @Conditional(value=TestCondition .class)
      public MyBean getTestConfigBean() {
          //TODO YOUR CODE;
      }

}

I would like to know if it is possible to specify confiugrationOnProperty with condition of havingValue != "value3"

我想知道是否可以指定 configurationOnProperty 的条件为 hasValue != "value3"

public class TestCondition2 implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String testValue = (context.getEnvironment().getProperty("test.configname");
        return ! "value3".equalsIgnoreCase("testValue");
    }

}

And then use it like this :

然后像这样使用它:

@Configuration
public class TestConfig {

      @Conditional(value=TestCondition2 .class)
      public MyBean getTestConfigBean() {
          //TODO YOUR CODE;
      }

}