Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Named annotations with Guice Providers

Tags:

guice

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"?

like image 733
emmby Avatar asked Feb 12 '13 18:02

emmby


People also ask

What is @named annotation in Guice?

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) { ... }

What is a provider in Guice?

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.

What is @named annotation in Java?

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.

What are bindings in Guice?

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.


1 Answers

I just wrote a test, it does exactly what you want it to: https://gist.github.com/jangalinski/4943871

like image 154
Jan Galinski Avatar answered Oct 05 '22 08:10

Jan Galinski