gpt4 book ai didi

java - Guice MapBinder

转载 作者:行者123 更新时间:2023-11-30 06:35:18 29 4
gpt4 key购买 nike

我在 Java + Kotlin 项目中使用 Guice 将算法实现映射注入(inject)到特定的 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")))

它就在那里。怎么了?

最佳答案

问题在于 Kotlin 泛型!= Java 泛型。

这段 Kotlin 代码。

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

编译为

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

当注入(inject)Guice时正在寻找Map<String, ? extends SchedulingAlgorithm>它没有像 MapBinder 这样的绑定(bind)创建了 Map<String, SchedulingAlgorithm> 的绑定(bind).

关于java - Guice MapBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287126/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com