CDI:两个生产者

时间:2017-06-05 13:34:57

标签: java-ee cdi

我有生产者:

@Produces 
public IPaymentGateway getStripePaymentGateway(@StripeApiKey final String apiKey) {
   return new StripeFluentAPI(apiKey);
}

@Produces
public IPaymentGateway getStripePaymentGatewayProxy() {
    IPaymentGateway gateway = mock(IPaymentGateway.class);
    ICustomer customer = mock(ICustomer.class);

    when(gateway.customer()).thenReturn(customer);

    return gateway;
}

第一个返回我IPaymentGateway的真实实现。另一方面,第二个返回代理对象。

我使用@ApplicationScoped对象来了解是否必须启用或禁用网关:

@ApplicationScoped
public class ConfigurationResources {
    public boolean isPaymentGatewayEnabled() {
        return paymentGatewayEnabled;
    }
}

所以,我想知道如何根据isPaymentGatewayEnabled值选择on或其他制作人。

1 个答案:

答案 0 :(得分:1)

由于您的ConfigurationResources是CDI bean(@ApplicationScoped),因此它也是可注射的。您可以使用它并以这种方式进行生产者注射:

@Produces 
public IPaymentGateway getStripePaymentGateway(@StripeApiKey final String apiKey, ConfigurationResources configResource) {
   if (configResource.isEnabled()) {
     return new StripeFluentAPI(apiKey);
   } else {
     IPaymentGateway gateway = mock(IPaymentGateway.class);
     ICustomer customer = mock(ICustomer.class);
     when(gateway.customer()).thenReturn(customer);
     return gateway;
   }
}

因此,这将基于configResource.isEnabled()创建结果。