java根据配置文件中的变量使用不同的bean实现
我有两颗豆子:
@Component("FierstClient")
public class FierstClient implements CryptoClient {
及
@Component("SecondClient")
public class SecondClient implements CryptoClient {
我有以下服务:
@Component
public class CryptoServiceImpl implements CryptoService {
private final Marshaler marshaler;
private final CryptoClient cryptoClient;
public CryptoServiceImpl(Marshaler marshaler,
@Qualifier("FirstClient") CryptoClient cryptoClient) {
this.marshaler = marshaler;
this.cryptoClient = cryptoClient;
}
现在我有一个任务-移动来控制这个bean配置文件。我知道一些解决方案,但它们对我来说似乎很幼稚:
创建配置
default-server: first // or second
并在CryptoServiceImpl
中注入2个bean:@Qualifier(“FirstClient”)CryptoClient cryptoClientFirst @限定符(“SecondsClient”)CryptoClient cryptoClientSecond
当我使用它时,写下:
if(default-server equals first)...else...
- 创建
Profile
。但我会有另一个配置,如DB等。我会有许多组合的亵渎,如:
FirstClientAndPosgresqlProfile FirstClientAndOracleProfile SecondClientAndPosgresqlProfile SecondClientAndOracleProfile
如果我有更多可变参数,我会有新的配置文件
可能存在依赖于配置文件中的变量使用不同bean实现的明确解决方案
# 1 楼答案
你可以用这样的东西
您需要将
enable.client
属性设置为first
或second
。如果属性不存在DefaultClient
将被实例化另一种方法是将
@ConditionalOnProperty
移动到@Component
定义之上。在这种情况下,您将不再需要上面的@Configuration