Spring @ConditionalOnProperty havingValue = “value1” or “value2”

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.

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 {

    }

}

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

@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.

Leave a Comment