单个提供程序,它基于类绑定创建不同类型的对象

时间:2016-02-16 05:15:47

标签: java guice

我正在尝试注入多个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}}

但我无法弄清楚如何指定类注入依赖

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>>(){});