Java Guice 注入泛型类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24657127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Guice injecting Generic type
提问by petomalina
I'am trying to Inject generic type with Guice. I have Repository< T > which is located in the Cursor class.
我正在尝试使用 Guice 注入泛型类型。我有位于 Cursor 类中的 Repository< T > 。
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?
因此,当我创建 Cursor<User> 时,我还希望 Guice 将我的存储库注入到 Repository<User>。有没有办法做到这一点?
采纳答案by gontard
You have to use a TypeLiteral
:
你必须使用一个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:
要获取 的实例Cursor<T>
,Injector
需要一个:
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.
常见问题解答中的更多详细信息。