Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know why you want to do this. But I would not mix up construction code (which is dependency injection configuration) with business logic. If you do that, your business logic might not be understandable anymore. And to me it seems, that your conditional injection depends on the situation, i.e. an input from a user interface.</p> <p>So why not just inject both and make the condition explicit? I'd prefer that. An example app:</p> <pre><code>public class MyModule extends AbstractModule { @Override protected void configure() { } public static void main(String[] args) { MyModule module = new MyModule(); Injector injector = Guice.createInjector(module); Order order = injector.getInstance(Order.class); order.finishOrder(PaymentMethod.CARD); } } public class PaymentProvider { private final Payment cashPayment, cardPayment; @Inject public PaymentProvider(CardPayment cardPayment, CashPayment cashPayment) { this.cardPayment = cardPayment; this.cashPayment = cashPayment; } public Payment getPaymentByMethod(PaymentMethod method) { switch (method) { case CARD: return cardPayment; case CASH: return cashPayment; default: throw new IllegalArgumentException("Unkown payment method: " + method); } } } public enum PaymentMethod { CASH, CARD } public class Order { private final PaymentProvider paymentProvider; @Inject public Order(PaymentProvider paymentProvider) { this.paymentProvider = paymentProvider; } public void finishOrder(PaymentMethod method) { paymentProvider.getPaymentByMethod(method).pay(); } } </code></pre> <p>Still for your own practise: The Payment stuff. You do not need any Guice code in there. The rest is done by Guice automagically. If you start using interfaces you would have start to use bindings as described here: <a href="http://code.google.com/p/google-guice/wiki/GettingStarted">http://code.google.com/p/google-guice/wiki/GettingStarted</a>. But if you do not have any interfaces, the construction is done without any configuration. The @Inject annotations are enough.</p> <p>Of course this is just an example design. But it shows how easy it is to setup a nicely decoupled Java app with Guice.</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