有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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配置文件。我知道一些解决方案,但它们对我来说似乎很幼稚:

  1. 创建配置default-server: first // or second并在CryptoServiceImpl中注入2个bean:

    @Qualifier(“FirstClient”)CryptoClient cryptoClientFirst @限定符(“SecondsClient”)CryptoClient cryptoClientSecond

当我使用它时,写下:

if(default-server equals first)...else...
  1. 创建Profile。但我会有另一个配置,如DB等。我会有许多组合的亵渎,如:

FirstClientAndPosgresqlProfile FirstClientAndOracleProfile SecondClientAndPosgresqlProfile SecondClientAndOracleProfile

如果我有更多可变参数,我会有新的配置文件

可能存在依赖于配置文件中的变量使用不同bean实现的明确解决方案


共 (1) 个答案

  1. # 1 楼答案

    你可以用这样的东西

    @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 {
    }