2017-06-05 27 views
0

我不得不生产者: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值。

+1

您可以产生'IPaymentGateway'一个方法,并添加'ConfigurationResources'作为该方法的参数。然后,您可以生成“真实”bean或“isPaymentGatewayEnabled”值上的模拟依赖。 – Rouliboy

回答

1

由于您ConfigurationResources是一个CDI豆(@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()结果。