我有 2 个豆子:
@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 @Qualifier("SecondsClient") CryptoClient cryptoClientSecond
当我使用它时写:
if(default-server equals first)...else...
Profile
. 但是我会不会有其他配置,比如 DB 等等。回答我会有很多配置文件,比如:FirstClientAndPosgresqlProfile FirstClientAndOracleProfile SecondClientAndPosgresqlProfile SecondClientAndOracleProfile
...
如果我有更多可更改的参数,我会有新的配置文件吗?
可能存在依赖于配置文件中的变量使用不同 bean 实现的明确解决方案?
你可以使用这样的东西
@Configuration
public class ClientConfig {
@Bean(name="criptoClient")
@ConditionalOnProperty(
name = "enabled.client",
havingValue = "first")
public CryptoClient firstClient() {
// return first client
}
@Bean(name="criptoClient")
@ConditionalOnProperty(
name = "enabled.client",
havingValue = "second")
public CryptoClient secondClient() {
// return second client
}
@Bean(name="criptoClient")
@ConditionalOnProperty(
name = "enabled.client",
matchIfMissing = true)
public CryptoClient defaultClient() {
// return default client
}
}
您需要将该enable.client
属性设置为first
或second
。如果该属性不存在,则会DefaultClient
被实例化。
另一种方法是将 移动到@ConditionalOnProperty
您的@Component
定义之上。在这种情况下,您将不再需要上述@Configuration
.
@Component("criptoClient")
@ConditionalOnProperty(
name = "enabled.client",
havingValue = "first")
public class FierstClient implements CryptoClient {
}
@Component("criptoClient")
@ConditionalOnProperty(
name = "enabled.client",
havingValue = "second")
public class SecondClient implements CryptoClient {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句