Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice injecting Generic type

Tags:

I'am trying to Inject generic type with Guice. I have Repository< T > which is located in the Cursor class.

public class Cursor<T> {      @Inject     protected Repository<T> repository; 

So when I create Cursor< User >, I also want the Guice to inject my repository to Repository< User >. Is there a way to do this?

like image 210
petomalina Avatar asked Jul 09 '14 15:07

petomalina


People also ask

What does @inject do Guice?

Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.

What is @inject annotation in Guice?

Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.

How do you inject a Guice class?

The implementation is very easy to understand. We need to create Injector object using Guice class createInjector() method where we pass our injector class implementation object. Then we use injector to initialize our consumer class. If we run above class, it will produce following output.

Can Guice inject null?

Guice forbids null by default So if something tries to supply null for an object, Guice will refuse to inject it and throw a NULL_INJECTED_INTO_NON_NULLABLE ProvisionException error instead. If null is permissible by your class, you can annotate the field or parameter with @Nullable .


1 Answers

You have to use a TypeLiteral:

import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral;  public class MyModule extends AbstractModule {    @Override   protected void configure() {     bind(new TypeLiteral<Repository<User>>() {}).to(UserRepository.class);   } } 

To get an instance of Cursor<T>, an Injector is required:

import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral;  public class Main {    public static void main(String[] args) {     Injector injector = Guice.createInjector(new MyModule());     Cursor<User> instance =          injector.getInstance(Key.get(new TypeLiteral<Cursor<User>>() {}));     System.err.println(instance.repository);   } } 

More details in the FAQ.

like image 95
gontard Avatar answered Sep 21 '22 06:09

gontard