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