gpt4 book ai didi

java - 根据配置文件中的变量使用不同的bean实现

转载 作者:行者123 更新时间:2023-12-02 01:53:38 28 4
gpt4 key购买 nike

我有 2 颗 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;
}

现在我有一个任务 - 控制这个 beans 配置文件。我知道一些解决方案,但它们对我来说似乎很天真:

  1. 创建配置default-server:第一个//或第二个并在CryptoServiceImpl中注入(inject)2个bean:

    @Qualifier("FirstClient") CryptoClient cryptoClientFirst@Qualifier("SecondsClient") CryptoClient cryptoClientSecond

当我使用它时写:

if(default-server equals first)...else...
  • 创建个人资料。但是我会有其他配置,如数据库等。我会有很多配置文件,其组合如下:
  • 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 属性设置为 firstsecond。如果该属性不存在,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 {
    }

    关于java - 根据配置文件中的变量使用不同的bean实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52610498/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com