Search code examples
jakarta-eecdi

CDI: Two producers


I have to producers:

@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;
}

The first one returns a real implementation of my IPaymentGateway. By other side, the second one returns a proxied object.

I'm using an @ApplicationScoped object in order to know if the gateway has to be enabled or disabled:

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

So, I'd like to know how to select on or other producers according isPaymentGatewayEnabled value.


Solution

  • Since your ConfigurationResources is a CDI bean (@ApplicationScoped) it is also injectable. You can make use of that and go for producer injection in approximately this way:

    @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;
       }
    }
    

    Therefore, this will create a result based on configResource.isEnabled().