I'm using Guice for dependency injection and I'm a bit confused. There are two Named
annotations in different packages:
com.google.inject.name.Named
and javax.inject.Named
(JSR 330?).
I'm eager to depend on javax.inject.*
. Code sample:
import javax.inject.Inject;
import javax.inject.Named;
public class MyClass
{
@Inject
@Named("APrefix_CustomerTypeProvider")
private CustomerTypeProvider customerTypeProvider;
}
In my naming module I may have the following line:
bind(CustomerTypeProvider.class).annotatedWith(...).toProvider(CustomerTypeProviderProvider.class);
The question: I'm curious what should I put where the dots are? I would expect something like com.google.inject.name.Names.named("APrefix_CustomerTypeProvider")
but this one returns com.google.inject.name.Named
while I need the one in javax.inject
.
CustomerTypeProviderProvider.class.getAnnotation(javax.inject.Named.class)
also does not fit well because the CustomerTypeProviderProvider
(ignore the stupid name, legacy issue) is not annotated.
As mentioned on the Guice wiki, both work the same . You shouldn't worry about that. It is even recommended to use javax.inject.*
when available, just as you prefer too (bottom of the same page).
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.name.Names;
import javax.inject.Inject;
public class Main {
static class Holder {
@Inject @javax.inject.Named("foo")
String javaNamed;
@Inject @com.google.inject.name.Named("foo")
String guiceNamed;
}
public static void main(String[] args) {
Holder holder = Guice.createInjector(new AbstractModule(){
@Override
protected void configure() {
// Only one injection, using c.g.i.Names.named("").
bind(String.class).annotatedWith(Names.named("foo")).toInstance("foo");
}
}).getInstance(Holder.class);
System.out.printf("javax.inject: %s%n", holder.javaNamed);
System.out.printf("guice: %s%n", holder.guiceNamed);
}
}
Prints:
java.inject: foo
guice: foo
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.