Guice注入泛型类型

Guice注入泛型类型

本文介绍了Guice注入泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Guice注入泛型。我有知识库< T>,它位于Cursor类中。

  public class Cursor< T> {

@Inject
受保护的信息库< T>库;

所以当我创建Cursor<用户>,我也希望Guice将我的资源库注入到Repository<用户>。有没有办法做到这一点?

解决方案

您必须使用: p>

  import com.google.inject.AbstractModule; 
import com.google.inject.TypeLiteral;

public class MyModule extends AbstractModule {

@Override
protected void configure(){
bind(new TypeLiteral< Repository< User>>( ){})。(UserRepository.class);


$ / code>

要得到一个的实例, Cursor< T> ,一个注射器是必需的:

  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){
Inject injector = Guice.createInjector(new MyModule());
光标<用户> instance =
injector.getInstance(Key.get(new TypeLiteral< Cursor< User>>(){}));
System.err.println(instance.repository);


更多详情。


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?

解决方案

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.

这篇关于Guice注入泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:08