P44*_*44T 14 java spring spring-boot
Spring Boot使用@ConfigurationProperties注释为我们提供了类型化的配置对象.其中一个优点是在使用Spring Boot注释处理器时可以在IDE中免费获取属性名称.另一个是:验证.
现在,我想根据属性的值来制作一个bean.实际上,我有两个接口的实现,这个属性告诉我应该使用哪一个.我可以像这样实现它:
ImplementationA.java
@Component
@ConditionalOnProperty(name = "foo.bar", havingValue = "a")
public class ImplementationA implements SomeInterface { ... }
Run Code Online (Sandbox Code Playgroud)
ImplementationB.java
@Component
@ConditionalOnProperty(name = "foo.bar", havingValue = "b")
public class ImplementationB implements SomeInterface { ... }
Run Code Online (Sandbox Code Playgroud)
application.yml
foo:
bar: "a"
Run Code Online (Sandbox Code Playgroud)
但是,我会失去打字配置的优势.所以我想在一个@ConfigurationProperties对象中声明这个属性:
FooProperties.java
@ConfigurationProperties(prefix = "foo")
public class FooProperties {
private String bar;
public String getBar() { ... }
public void setBar(String bar) { ... }
}
Run Code Online (Sandbox Code Playgroud)
这仍然可以工作,但是当我bar在这个类中声明一个默认值时,它显然不会被拾取,@ConditionalOnProperty因为这个注释Environment直接对应(如设计).所以也许最好不要混合这些概念.
是否有办法根据@ConfigurationProperties对象中的值设置条件bean ?最好使用一些@Conditional注释而不创建@Configurationbean,因为这意味着样板代码.
小智 1
它可能不那么性感,但一个潜在的解决方案可能是将您的配置自动连接到 SomeInterfaceConfiguration 中,该配置创建基于 FooProperties 的服务实现。
IE
@Configuration
public class SomeInterfaceConfiguration {
@Bean
@Autowired
public SomeInterface someInterface(FooProperties fooProperties){
if("a".equals(fooProperties.getBar()){
return SomeInterfaceImplementationA();
} else {
return SomeInterfaceImplementationB();
}
}
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用配置文件,但它与您想要的解决方案不同。即有一个默认实现。
@Component
public class ImplementationA
@Profile("b")
@Primary
@Component
public class ImplementationB
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1831 次 |
| 最近记录: |