Reputation: 697
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?
Upvotes: 0
Views: 1069
Reputation: 95614
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
.)
Upvotes: 0
Reputation: 35417
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.
Upvotes: 2