Spring Boot 使用 @ConfigurationProperties
注释为我们提供了类型化的配置对象。优点之一是在使用 Spring Boot 注释处理器时可以免费在 IDE 中完成属性名称。另一个是:验证。
现在,我想让 bean 以属性的值为条件。实际上,我有两个接口(interface)实现,这个属性告诉我应该使用哪一个。我可以这样实现它:
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
直接(按设计)。所以也许最好不要混合这些概念。
所以问题是……
是否有一种方法可以根据 @ConfigurationProperties
对象中的值创建条件 bean?最好使用一些 @Conditional
注释而不创建 @Configuration
bean,因为这意味着样板代码。
最佳答案
它可能没有那么性感,但一个潜在的解决方案可能是将您的配置 Autowiring 到 SomeInterfaceConfiguration 中,该配置创建提供基于 FooProperties 的服务实现。
即
@Configuration
public class SomeInterfaceConfiguration {
@Bean
@Autowired
public SomeInterface someInterface(FooProperties fooProperties){
if("a".equals(fooProperties.getBar()){
return SomeInterfaceImplementationA();
} else {
return SomeInterfaceImplementationB();
}
}
}
另一种选择是使用配置文件,但它与您想要的解决方案不同。 即有一个默认实现。
@Component
public class ImplementationA
@Profile("b")
@Primary
@Component
public class ImplementationB
关于java - Spring Boot bean 以 @ConfigurationProperties 值为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49153632/