Guice MapBinder

时间:2017-07-24 18:00:10

标签: java dependency-injection kotlin guice

我在Java + Kotlin项目中使用Guice将算法实现的映射注入特定的bean但我一直在

1) No implementation for java.util.Map<java.lang.String, ? extends com.scherule.scheduling.algorithms.SchedulingAlgorithm> annotated with @com.google.inject.name.Named(value=scheduling.algorithms) was bound.
  while locating java.util.Map<java.lang.String, ? extends com.scherule.scheduling.algorithms.SchedulingAlgorithm> annotated with @com.google.inject.name.Named(value=scheduling.algorithms)
    for the 2nd parameter of com.scherule.scheduling.SchedulingJobConsumer.<init>(SchedulingJobConsumer.kt:17)
  while locating com.scherule.scheduling.SchedulingJobConsumer

模块的定义如下定义:

class AlgorithmsModule : AbstractModule() {

    override fun configure() {
        MapBinder.newMapBinder(binder(),
                String::class.java,
                SchedulingAlgorithm::class.java,
                Names.named("scheduling.algorithms")
        ).addBinding("interval-projection").toInstance(IntervalProjectionAlgorithm())
    }

}

调用者代码是:

@Singleton
class SchedulingJobConsumer
@Inject constructor(
        @Named("scheduling.channel") channel: Channel,
        @Named("scheduling.algorithms") val schedulers: Map<String, SchedulingAlgorithm>
) : DefaultConsumer(channel) ...

但是当我做的时候

injector.getInstance(Key.get(new TypeLiteral<Map<String, SchedulingAlgorithm>>() {}, named("scheduling.algorithms")))
它就在那里。怎么了?

2 个答案:

答案 0 :(得分:0)

问题在于Kotlin Generics!= Java Generics。

这个Kotlin代码。

 @Named("scheduling.algorithms") val schedulers: Map<String, SchedulingAlgorithm>

获取编译为

Map<String, ? extends SchedulingAlgorithm> and not Map<String, SchedulingAlgorithm>

当注入时,Guice正在寻找没有绑定的Map<String, ? extends SchedulingAlgorithm>,因为MapBinderMap<String, SchedulingAlgorithm>创建了绑定。

答案 1 :(得分:0)

您可以尝试将以下成员方法添加到MapBinder,而不是使用AlgorithmsModule

@Provides
@Singleton
@Named("scheduling.algorithms")
fun schedulingAlgorithms(): Map<String, @JvmSuppressWildcards SchedulingAlgorithm> {
    return IntervalProjectionAlgorithm()
}