绑定注释与提供者方法的含义

The meaning of bindings annotation with provider methods

现在在看Guice的官方文档,看到了这段代码

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

上面代码中,@PayPal是什么意思? 在文档的页面中,我理解了原始绑定注释的含义。我们可以定制它。但是用法是这样的

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

在代码中,@PayPal表示这个参数processor应该被注入注解指示的实例。 那么,第一个代码到底是什么意思呢?

在第一个代码中,表示"when you find CreditCardProcessor annotated with @Paypal, use this method as provider"。

具体来说,第一个用于定义绑定,第二个用于请求绑定。

第一个,可以在configure()方法中作为规则重写:

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

但是......你实际上不能,因为那样你就会有一个单身人士。从来没有写过你想要一个单身人士。

所以 provide 方法是一个很好的工具,它允许您创建新实例并在传递它们之前对其进行初始化。

将注释视为方法 return 类型的一部分。您列出的 @Provides 方法不仅提供了 CreditCardProcessor,还提供了 @PayPal CreditCardProcessor。于是,方法写成@Provides @PayPal CreditCardProcessor.

然后您可以像第二次使用一样请求 @PayPal CreditCardProcessor,方法是在 @Inject 注释的方法或构造函数中注释参数,或者将注释添加到 @Inject-注释字段。 (您也可以通过创建 Key 直接从 Injector 实例请求它。)