Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using <a href="http://code.google.com/p/google-guice/wiki/Multibindings" rel="nofollow">MapBinder</a> extension you can get injected with several bindings contained in a <code>Map</code>. Then it's a matter of implementation which one to use.</p> <p>You will need a key, in your case that could be a <code>String</code> or <code>Enumeration</code> and bind all <code>Payment</code> implementations to the appropriate keys:</p> <pre><code>public class MyModule extends AbstractModule { @Override protected void configure() { // this one aggregates all bindings and could be further annotated if you // need several maps with same key/value types MapBinder&lt;String, Payment&gt; mapBinder = MapBinder.newMapBinder(binder(), String.class, Payment.class); // simple binding of PaymentCashImpl to 'cash' key mapBinder.addBinding("cash").to(PaymentCashImpl.class); // you can scope during binding or using @Singleton annotation on implementations mapBinder.addBinding("card").to(PaymentCardImpl.class).in(Singleton.class); } } </code></pre> <p>Then in <code>Order</code> you get injected with the whole map and decide which implementation to use:</p> <pre><code>public class Order { @Inject Map&lt;String, Provider&lt;Payment&gt;&gt; paymentProcessors; public void finishOrder(String paymentMethod) { if (!paymentProcessors.containsKey(paymentMethod)) { throw new IllegalArgumentException("Unknown payment method " + paymentMethod); } Payment paymentProcessor = paymentProcessors.get(paymentMethod).get(); // do your stuff... paymentProcessor.pay(); } } </code></pre> <p><strong>Note:</strong> Injecting providers doesn't work with <code>javax.inject.Provider</code>, you need to use <code>com.google.inject.Provider</code>.</p> <p>By injecting providers instead of instances you can achieve lazy instantiation and different instantiation policies per implementation. Like in the example above the <code>PaymentCardImpl</code> is singleton, while the other is created each time. You can use guice <a href="http://code.google.com/p/google-guice/wiki/Scopes" rel="nofollow">scopes</a> to control the lifespan, or even implement your own provider to accomplish something else.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload