简体   繁体   中英

The meaning of bindings annotation with provider methods

Now I'm reading Guice's official document and I saw this code.

    @Provides @PayPal
  CreditCardProcessor providePayPalCreditCardProcessor(
      @Named("PayPal API key") String apiKey) {
    PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
    processor.setApiKey(apiKey);
    return processor;
  }

In above code, what does @PayPal mean? In the page of the document, I understand the meaning of original binding annotations. We can customize it. But the usage is like this.

@Inject
  public RealBillingService(@PayPal CreditCardProcessor processor,
      TransactionLog transactionLog)

In the code, @PayPal means this parameter processor should be injected the instance indicated by the annotation. So, what exactly does it mean in the first code?

In the first code, it means "when you find CreditCardProcessor annotated with @Paypal , use this method as provider".

Concretely, the first one is used to define the binding, the second one is used to request the binding.

The first one, could be rewritten as a rule in the configure() method:

protected void configure() {
  PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
  processor.setApiKey(apiKey);
  bind(CreditCardProcessor.class).annotatedWith(PayPal.class).toInstance(processor);
}

But... you actually can't because then you'd have a singleton. Never it was written that you wanted a singleton.

So the provide methods are the nice tool to allow you making new instances and initializing them before passing them around.

Think of the annotation as part of the method's return type. The @Provides method you listed does not simply provide a CreditCardProcessor , it provides a @PayPal CreditCardProcessor . Thus, the method is written @Provides @PayPal CreditCardProcessor .

You can then request @PayPal CreditCardProcessor as in your second usage, by annotating a parameter in an @Inject -annotated method or constructor, or by adding the annotation to an @Inject -annotated field. (You can also request it directly from an Injector instance by creating a Key .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM