Spring @ConditionalOnProperty具有Value ="value1"或"value2" [英] Spring @ConditionalOnProperty havingValue = "value1" or "value2"
问题描述
我正在寻找configurationOnProperty
用法,可以在其中指定考虑多个值,如下所示
I am looking for configurationOnProperty
usage where I can specify to consider more than one value as shown below
例如:@ConditionalOnProperty(value = "test.configname", havingValue = "value1" or "value2")
OR
我想知道是否可以以havingValue != "value3"
例如:@ConditionalOnProperty(value = "test.configname", havingValue != "value3")
请让我知道是否可以通过spring boot
配置实现以上任一目的.
Please let me know if there is a way to achieve any one of the above in spring boot
configuration.
推荐答案
Spring Boot提供了 AllNestedConditions
和
Spring Boot provides AnyNestedCondition
for created a condition that will match when any nested condition matches. It also provides AllNestedConditions
and NoneNestedConditions
for matching when all nested conditions or no nested conditions match respectively.
对于要匹配value1
或value2
值的特定情况,您可以创建一个AnyNestedCondition
,如下所示:
For your specific case where you want to match a value of value1
or value2
you would create an AnyNestedCondition
like this:
class ConfigNameCondition extends AnyNestedCondition {
public ConfigNameCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnProperty(name = "test.configname", havingValue = "value1")
static class Value1Condition {
}
@ConditionalOnProperty(name = "test.configname", havingValue = "value2")
static class Value2Condition {
}
}
然后将其与@Conditional
一起使用,例如:
And then use it with @Conditional
, like this for example:
@Bean
@Conditional(ConfigNameCondition.class)
public SomeBean someBean() {
return new SomeBean();
}
如嵌套条件注释的javadoc中所示(链接到上面),嵌套条件可以是任何类型.在这种情况下,它们不必都具有相同的类型.
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.
这篇关于Spring @ConditionalOnProperty具有Value ="value1"或"value2"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!