I’m using Google Guice for dependency injection. Suppose I have the following:
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();
}
}
Following on from this, is a very simple module for binding, like so:
public class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(Payment.class).to(PaymentCashImpl.class);
}
}
As you can see, a Payment instance is injected into the Order constructor. This is done in the MyModule class and overall is really cool.
My main looks like:
public static void main(String[] args) {
MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);
Order order = injector.getInstance(Order.class);
order.finishOrder();
}
What I can’t see however, is how I could incorporate some way to conditionally bind either a PaymentCardImpl or a PaymentCashImpl instance to the Order constructor.
Let’s say for example, that the order was an ‘online’ order. I would then need to this:
bind(Payment.class).to(PaymentCardImpl.class);
What’s the best way to do this? I’m new to dependency injection.
You can annotate which one you want to inject. If you do a named binding it will resolve the issue.
See below:
Then where you want to inject you do:
or: