Note that there are some explanatory texts on larger screens.

plurals
  1. PODependency Injection based on a condition
    text
    copied!<p>I'm using Google Guice for dependency injection. Suppose I have the following:</p> <pre><code>public interface Payment { public void pay(); } public class PaymentCardImpl implements Payment { public void pay() { System.out.println("I pay with a card"); } } public class PaymentCashImpl implements Payment { public void pay() { System.out.println("I pay cash"); } } public class Order { private Payment payment; @Inject public Order(Payment payment){ this.payment=payment; } public void finishOrder(){ this.payment.pay(); } } </code></pre> <p>Following on from this, is a very simple module for binding, like so:</p> <pre><code>public class MyModule extends AbstractModule { @Override protected void configure() { bind(Payment.class).to(PaymentCashImpl.class); } } </code></pre> <p>As you can see, a <code>Payment</code> instance is injected into the Order constructor. This is done in the <code>MyModule</code> class and overall is really cool.</p> <p>My main looks like:</p> <pre><code>public static void main(String[] args) { MyModule module = new MyModule(); Injector injector = Guice.createInjector(module); Order order = injector.getInstance(Order.class); order.finishOrder(); } </code></pre> <p>What I can't see however, is how I could incorporate some way to conditionally bind either a <code>PaymentCardImpl</code> <strong><em>or</em></strong> a <code>PaymentCashImpl</code> instance to the <code>Order</code> constructor. </p> <p>Let's say for example, that the order was an 'online' order. I would then need to this:</p> <pre><code>bind(Payment.class).to(PaymentCardImpl.class); </code></pre> <p>What's the best way to do this? I'm new to dependency injection.</p>
 

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