我有生产者:
@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或其他制作人。
答案 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()
创建结果。