我正在尝试结合 Guice 的这 3 个特性:注入、多重绑定、泛型。我创建了一个生产项目的原型,所以这里是:
首先,这是泛型的一个小层次结构(在生产情况下,有 N 个实体的层次结构):
public interface Type {
}
public class Type1 implements Type{
}
public class Type2 implements Type {
}
接下来,我想通过Factory创建的类ToCreate1和ToCreate2。
基类:
public abstract class AbstractToCreate<T extends Type> {
public T type;
public Integer param;
public AbstractToCreate(T type, Integer param){
this.type = type;
this.param = param;
}
}
继承人:
public class ToCreate1 extends AbstractToCreate<Type1>{
@Inject
public ToCreate1(Type1 type, @Assisted Integer param) {
super(type, param);
}
}
public class ToCreate2 extends AbstractToCreate<Type2> {
@Inject
public ToCreate2(Type2 type, @Assisted Integer param) {
super(type, param);
}
}
然后,工厂本身:
public interface Factory<T extends Type> {
AbstractToCreate<T> create(Integer param);
}
所以,现在我想注入一张地图,其中包含Factory<Type1>和Factory<Type2>以分别创建ToInject1和ToInject2。
所以,我用 configure 方法创建了 Guice 的AbstractModule :
protected void configure() {
install(new FactoryModuleBuilder()
.implement(new TypeLiteral<AbstractToCreate<Type1>>(){}, ToCreate1.class)
.build(new TypeLiteral<Factory<Type1>>(){}));
install(new FactoryModuleBuilder()
.implement(new TypeLiteral<AbstractToCreate<Type2>>(){}, ToCreate2.class)
.build(new TypeLiteral<Factory<Type2>>(){}));
MapBinder<String, Factory> mapBinder = MapBinder.newMapBinder(binder(), String.class, Factory.class);
mapBinder.addBinding("type1").to(new TypeLiteral<Factory<Type1>>(){});
mapBinder.addBinding("type2").to(new TypeLiteral<Factory<Type2>>(){});
}
所以,我注入它@Inject public Map<String, Factory> map;
,一切都好:
Factory<Type1> factory1 = main.map.get("type1");
Factory<Type2> factory2 = main.map.get("type2");
AbstractToCreate<Type1> create1 = factory1.create(1);//create1 is ToCreate1 instance
AbstractToCreate<Type2> create2 = factory2.create(2);//create2 is ToCreate2 instance
正如我之前提到的,我的生产系统中有更多的类型,所以AbstractModule变得过于繁琐。我尽量避免重复代码和修改配置方法:
@Override
protected void configure() {
this.<Type1>inst(ToCreate1.class);
this.<Type2>inst(ToCreate2.class);
}
private <V extends Type> void inst(Class<? extends AbstractToCreate<V>> clazz) {
install(new FactoryModuleBuilder()
.implement(new TypeLiteral<AbstractToCreate<V>>(){}, clazz)
.build(new TypeLiteral<Factory<V>>(){}));
}
而且它不起作用!古斯 说:
1) ru.test.genericassistedinject.AbstractToCreate<V> cannot be used as a key; It is not fully specified.
怎么了?