我希望能够使用Guice注入通用接口的通用实现.
public interface Repository<T> {
void save(T item);
T get(int id);
}
public MyRepository<T> implements Repository<T> {
@Override
public void save(T item) {
// do saving
return item;
}
@Override
public T get(int id) {
// get item and return
}
}
Run Code Online (Sandbox Code Playgroud)
在C#中使用Castle.Windsor,我可以做到:
Component.For(typeof(Repository<>)).ImplementedBy(typeof(MyRepository<>))
Run Code Online (Sandbox Code Playgroud)
但我不认为Guice中存在等价物.我知道我可以TypeLiteral在Guice 中使用来注册个人实现,但是有没有办法像Windsor那样一次注册它们?
编辑:
这是一个用法示例:
Injector injector = Guice.createInjector(new MyModule());
Repository<Class1> repo1 = injector.getInstance(new Key<Repository<Class1>>() {});
Repository<Class2> repo2 = injector.getInstance(new Key<Repository<Class2>>() {});
Run Code Online (Sandbox Code Playgroud)
虽然更可能的用法是注入另一个类:
public class ClassThatUsesRepository {
private Repository<Class1> repository;
@Inject
public ClassThatUsesRepository(Repository<Class1> …Run Code Online (Sandbox Code Playgroud) 我能够使下面的通用方法工作的唯一方法是传递看似冗余的TypeLiteral<Set<T>>参数.我认为应该可以在给定其他参数的情况下以编程方式构造此参数,但无法弄清楚如何.
protected <T> Key<Set<T>> bindMultibinder(
TypeLiteral<Set<T>> superClassSet, TypeLiteral<T> superClass) {
final Key<Set<T>> multibinderKey = Key.get(superClassSet, randomAnnotation);
return multibinderKey;
}
Run Code Online (Sandbox Code Playgroud)
客户端代码如下:
bindMultibinder(new TypeLiteral<Set<A<B>>>(){}, new TypeLiteral<A<B>>(){});
Run Code Online (Sandbox Code Playgroud)
其中A和B是接口.
如果我尝试以下(删除TypeLiteral<Set<T>> superClassSet参数),我会收到java.util.Set<T> cannot be used as a key; It is not fully specified.运行时错误.
protected <T> Key<Set<T>> bindMultibinder(TypeLiteral<T> superClass) {
final Key<Set<T>> multibinderKey = Key.get(
new TypeLiteral<Set<T>>() {}, randomAnnotation);
return multibinderKey;
}
Run Code Online (Sandbox Code Playgroud) 我看过这篇关于注册泛型类型的帖子.
如何注册的例子:
bind(new TypeLiteral<Dal<RoutingResponse>>() {}).to((Class<? extends Dal<RoutingResponse>>) ResponseDal.class);
Run Code Online (Sandbox Code Playgroud)
但是如何从进样器中获取泛型类型的实例?
我试过了:
injector.getInstance(Dal<RoutingResponse>().getClass());
Run Code Online (Sandbox Code Playgroud)
但有编译错误.
我该怎么写呢?