2017-06-05 21 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()結果。