Java – dependency injection is condition based

I'm using Google Guice for dependency injection Suppose I have the following points:

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();
    }
}

Next is a very simple binding module, like this:

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Payment.class).to(PaymentCashImpl.class);
    }
}

As you can see, the payment instance is injected into the order constructor This is done in the mymodule class. Overall, it's 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 don't see, however, is how I can combine some way to conditionally bind paymentcardimpl or paymentcashimpl instances to the order constructor

For example, an order is an "online" order I will need to do this:

bind(Payment.class).to(PaymentCardImpl.class);

What's the best way to do it? I'm new here

Solution

You can comment which one to inject If you make a named binding, it will solve the problem

See below:

bind(Payment.class).annotatedWith(Names.named("Card")).to(PaymentCardImpl.class);

bind(Payment.class).annotatedWith(Names.named("Cash")).to(PaymentCashImpl.class);

Then you want to inject what you do:

@Named("Cash") Payment payment

or

@Named("Card") Payment payment
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>