我正在尝试注入多个datastax
Mapper
,但Provider
创建代码始终相同,为每种类型编写提供程序是多余的。
提供商代码是
public class FooMapperProvider extends Provider<Mapper<Foo>> () {
private final MappingManager mappingManager
@Inject
FooMapperProvider(MappingManager) {
this.mappingManager = mappingManager;
}
@Override
public Mapper<Foo> get() {
mappingManager.mapper(Foo.class);
}
}
是否可以绑定或创建
的提供程序bind(Foo.class).toProvider(GenericMapperProvider.class)
bind(Bar.class).toProvider(GenericMapperProvider.class)
以get
方式调用mappingManager.mapper
public class MapperProvider<T> implements Provider<Mapper<T>> {
private final MappingManager mappingManager;
private final Class klass;
@Inject
public MapperProvider(MappingManager mappingManager, Class klass) {
this.mappingManager = mappingManager;
this.klass = klass;
}
@Override
public Mapper<T> get() {
return mappingManager.mapper(klass);
}
}
可以根据特定绑定的类创建映射器吗?
我想过尝试像
这样的东西{{1}}
但我无法弄清楚如何指定类和注入依赖
答案 0 :(得分:1)
public class MapperProvider<T> implements Provider<Mapper<T>> {
private final MappingManager mappingManager;
private final TypeLiteral<T> type;
@Inject
public MapperProvider(MappingManager mappingManager, TypeLiteral<T> type) {
this.mappingManager = mappingManager;
this.type = type;
}
@Override
public Mapper<T> get() {
return mappingManager.mapper(type.getRawType());
}
}
bind(new TypeLiteral<Mapper<Foo>>(){})
.toProvider(new TypeLiteral<MapperProvider<Foo>>(){});