I have two named instances of a type bound in my application:
bind(Foo.class).toProvider(FooProvider.class);
bind(Foo.class).annotatedWith(Names.named("prime")).toProvider(FooPrimeProvider.class);
I have a class that would like to use one instance of each. For technical reasons, this class cannot inject the instances directly, it must inject a provider to the instances:
class Bar {
@Inject static Provider<Foo> fooProvider;
@Inject @Named("prime") static Provider<Foo> fooPrimeProvider; // WRONG!
}
The problem is that the FooPrime injection above is not injecting an instance named "prime", it's injecting a Provider named "prime", which of course is not what I want.
How do I tell Guice to inject a provider for the Foo instance named "prime"?
Guice comes with a built-in binding annotation @Named that takes a string: public class RealBillingService implements BillingService { @Inject public RealBillingService(@Named("Checkout") CreditCardProcessor processor, TransactionLog transactionLog) { ... }
Providers are used in numerous ways by Guice: When the default means for obtaining instances (an injectable or parameterless constructor) is insufficient for a particular binding, the module can specify a custom Provider instead, to control exactly how Guice creates or obtains instances for the binding.
This annotation indicates that the class is a named bean. You can specify a name to the named bean by adding an argument to the @Named annotation. For example, @Named("myBean") . If no name is specified, the Java class name is used as the name by default, with the first character converted to lowercase characters.
A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.
I just wrote a test, it does exactly what you want it to: https://gist.github.com/jangalinski/4943871
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With