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)
您可以使用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)
归档时间: |
|
查看次数: |
2276 次 |
最近记录: |