【发布时间】:2018-08-15 15:45:31
【问题描述】:
Spring Boot 使用 @ConfigurationProperties 注解为我们提供了类型化的配置对象。优点之一是在使用 Spring Boot 注释处理器时可以免费在 IDE 中完成属性名称。另一个是:验证。
现在,我想让 bean 以属性的值为条件。实际上,我有两个接口实现,这个属性告诉我应该使用哪一个。我可以这样实现它:
ImplementationA.java
@Component
@ConditionalOnProperty(name = "foo.bar", havingValue = "a")
public class ImplementationA implements SomeInterface { ... }
ImplementationB.java
@Component
@ConditionalOnProperty(name = "foo.bar", havingValue = "b")
public class ImplementationB implements SomeInterface { ... }
application.yml
foo:
bar: "a"
但是,我会失去类型化配置的优势。所以我想在@ConfigurationProperties 对象中声明这个属性:
FooProperties.java
@ConfigurationProperties(prefix = "foo")
public class FooProperties {
private String bar;
public String getBar() { ... }
public void setBar(String bar) { ... }
}
这仍然有效,但是当我在此类中声明 bar 的默认值时,@ConditionalOnProperty 显然不会拾取它,因为此注释直接针对 Environment 操作(按设计)。所以也许最好不要混合这些概念。
所以问题是……
有没有办法让条件 bean 基于 @ConfigurationProperties 对象中的值?最好使用一些 @Conditional 注释而不创建 @Configuration bean,因为这意味着样板代码。
【问题讨论】:
-
@ConfigurationProperties远低于@Conditional...组件扫描链中的注释。因此,我认为这是不可能的。所有@Conditional注释,如@Condition、@ConditionalOnProperty和@ConditionalOnExpression,都在@ConfigurationProperties之前执行 -
不能同时使用吗?像以前一样创建 FooProperties,但添加一个具有默认值的静态常量,并在 ConditionalOnProperty 的“havingValue”属性中引用它
-
您找到问题的答案了吗?
标签: java spring spring-boot