Guice injecting Generic type

前端 未结 1 1893
死守一世寂寞
死守一世寂寞 2020-12-17 09:18

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

public class Cursor {

    @Inject
          


        
相关标签:
1条回答
  • 2020-12-17 09:57

    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.

    0 讨论(0)
提交回复
热议问题