【问题标题】:CDI: Two producersCDI:两个生产商
【发布时间】:2017-06-06 18:56:04
【问题描述】:

我必须对制片人:

@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或其他生产者。

【问题讨论】:

  • 您可以使用一个方法生成IPaymentGateway,并将ConfigurationResources 添加为该方法的参数。然后,您可以根据 isPaymentGatewayEnabled 值生成“真实”bean 或模拟。

标签: jakarta-ee cdi


【解决方案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() 的结果。

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 2019-07-19
    • 1970-01-01
    • 2023-03-29
    • 2015-04-08
    • 1970-01-01
    • 2022-10-12
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多