2017-06-05 10 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の実際の実装を返します。反対側では、2番目のプロキシはプロキシされたオブジェクトを返します。私がどのように選択するかを知りたいのですが、そう

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

または他の生産者はisPaymentGatewayEnabled値に従って:

ために、私は、ゲートウェイを有効または無効にする必要があるかどうかを知るために@ApplicationScopedオブジェクトを使用しています。

+1

「IPaymentGateway」を生成するメソッドを1つ用意し、このメソッドのパラメータとして「ConfigurationResources」を追加することができます。次に、 "本物の" beanか、isPaymentGatewayEnabledの値に依存している模様を作ることができます。 – Rouliboy

答えて

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()に基づいて結果を作成します。