Spring @CondiitonalOnProperty,仅在缺少时如何匹配

XZe*_*Zen 6 java spring spring-boot

我有两种工厂方法:

@Bean
@ConditionalOnProperty("some.property.text")
public Apple createAppleX() {}
Run Code Online (Sandbox Code Playgroud)

@Bean
@ConditionalOnProperty("some.property.text", matchIfMissing=true)
public Apple createAppleY() {}
Run Code Online (Sandbox Code Playgroud)

如果根本不具有“ some.property.text”属性,则第二种方法可以正常工作,第一种方法将被忽略,这是理想的行为。

如果我们将某些字符串设置为“ some.property.text”,则这两种方法都被认为对生成Apple对象有效,这会导致应用程序失败,并显示错误“没有类型的合格bean”。

如果属性具有某些价值,是否可以避免将第二种方法视为工厂方法?特别是,仅通过注释是否有可能?

小智 11

我遇到了同样的问题,这是我的解决方案:

@Bean
@ConditionalOnProperty("some.property.text")
public Apple createAppleX() {}

@Bean
@ConditionalOnProperty("some.property.text", matchIfMissing=true, havingValue="value_that_never_appears")
public Apple createAppleY() {}
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,对于布尔情况,这个解决方案非常干净,第一个条件为havingValue=true,第二个条件为havingValue=false,这样你就不必使用随机值 (2认同)

And*_*son 8

您可以使用NoneNestedConditions来否定一个或多个嵌套条件。像这样的东西:

class NoSomePropertyCondition extends NoneNestedConditions {

    NoSomePropertyCondition() {
        super(ConfigurationPhase.PARSE_CONFIGURATION);
    }

    @ConditionalOnProperty("some.property.text")
    static class SomePropertyCondition {

    }

}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在您的 bean 方法之一上使用此自定义条件:

@Bean
@ConditionalOnProperty("some.property.text")
public Apple createAppleX() {}

@Bean
@Conditional(NoSomePropertyCondition.class)
public Apple createAppleY() {}
Run Code Online (Sandbox Code Playgroud)