春季@CondiitonalOnProperty,如何仅在缺少时才匹配

2022-09-03 00:17:27

我有两种工厂方法:

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

@Bean
@ConditionalOnProperty("some.property.text", matchIfMissing=true)
public Apple createAppleY() {}

如果根本没有“some.property.text”属性 - 第二种方法工作正常,第一个方法被忽略,这是所需的行为。

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

如果我们对属性有一些价值,是否可以避免将第二种方法视为工厂方法?特别是,是否可以仅通过注释来实现?


答案 1

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

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

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

答案 2

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

class NoSomePropertyCondition extends NoneNestedConditions {

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

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

    }

}

然后,您可以在其中一个 Bean 方法上使用此自定义条件:

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

@Bean
@Conditional(NoSomePropertyCondition.class)
public Apple createAppleY() {}

推荐