【问题标题】:Guice Multibinder Doesn't Work with Play FrameworkGuice Multibinder 不适用于 Play 框架
【发布时间】:2016-11-07 20:03:33
【问题描述】:

将 Play 2.5.8 与 Scala 2.11.8 结合使用。

我有一个 trait RequestMatcher 和它的多个实现。我想在我的服务中注入Seq[RequestMatcher]。我的模块如下所示:

class FeignModule(environment: Environment, configuration: Configuration) extends AbstractModule with AkkaGuiceSupport {
  def configure() = {
    val requestMatcherBinder = Multibinder.newSetBinder(binder(), classOf[RequestMatcher])
    // TODO: Allow for user specified matchers
    requestMatcherBinder.addBinding().to(classOf[DefaultPathMatcher])
    requestMatcherBinder.addBinding().to(classOf[DefaultMethodMatcher])
    requestMatcherBinder.addBinding().to(classOf[DefaultQueriesMatcher])
    requestMatcherBinder.addBinding().to(classOf[DefaultHeadersMatcher])
    requestMatcherBinder.addBinding().to(classOf[DefaultBodyMatcher])

    // TODO: Allow for user specified actors
    bindActor[DefaultRecordingService]("recordingService")
  }
}

注入目标如下:

@javax.inject.Singleton
class FeignService @Inject()(@Named("recordingService") val recordingService: ActorRef,
                             val feignProperties: FeignProperties,
                             val matchers: Seq[RequestMatcher])
                            (implicit val ec: ExecutionContext) {
}

但是

play.api.UnexpectedException: 意外异常[ProvisionException: 无法预配,请参阅以下错误:

1) 没有实现 scala.collection.Seq 是 边界。定位时 scala.collection.seq 对于service.FeignService.(FeignService.scala:19)的第三个参数

我知道 Play 读取了模块,因为 Actor(FeignService 的第一个参数)被注入得很好。我在类路径上也有 guice-multibindings jar。

怎么了?

【问题讨论】:

  • Multibindings 的 SetBinder 只适用于注入 Set,而不是有序的 Java List 或 Scala Seq。您可以使用 @Provides 方法使用 Set 处理 Seq 注入请求,但除非您定义/实现顺序,否则顺序将是未定义的。
  • @JeffBowman "Multibindings 的 SetBinder 只适用于注入 Set" 我认为这不是真的。根据他们的doc,“如果需要,也可以注入 Collection>。”。此外,我也试过Set,没有雪茄。
  • 是的,在 Set<Provider<T>> 或 Map<K, Provider<T>> 的意义上分别用于 Multibinder 和 MapBinder,Collection<T> 和 Collection<Provider<T>> 别名为 Sets,但不是任意 Collection 子类型,当然不是 Scala序列或设置。确保我们在这里讨论的是 java.util.Set。
  • 我也遇到了同样的问题,请问您找到解决方案了吗?
  • @codeCruncher 不,我要创建一个容器类

标签: scala playframework dependency-injection guice


【解决方案1】:

线程有点旧,但如果有人(像我一样)有同样的问题:正确答案在 cmets 中,但可能被忽略了:guice Multibinder 注入 Java 集合,而不是 Scala 集合

【讨论】:

  • 我爱你。您可以注入 java.util.Set 然后使用 scala.collection.JavaConverters._ 转换回 scala 集合
猜你喜欢
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
相关资源
最近更新 更多