【问题标题】:Fail to wire play dependancies with Macwire无法使用 Magwire 连接播放依赖项
【发布时间】:2017-12-07 20:46:32
【问题描述】:

我有一个依赖于 play 的 Configuration 和 WSClient 实例的 api 服务类。

我不想使用 @Inject() 注释,因为我想在 Macwire 上使用编译时注入,所以我所做的是:

// this is a trait that here im wiring all the dependencies that my api service needs
trait ApiDependencies {

  lazy val conf: Configuration = wire[Configuration]
  lazy val wsc: WSClient = wire[WSClient]

}


// this is the api service

class ApiService extends ApiDependencies {

  def getInfo (id: String): Future[Option[Info]] = {
    wsc.url("...").withHttpHeaders(("Content-Type", "application/json")).get.map { response =>
      response.status match {
        case Status.OK => ...
        case Status.NO_CONTENT => ...
        case _ => throw new Exception()
      }
    }
  }
}

但我得到一个编译器错误:

错误:找不到类型的值:[com.typesafe.config.Config]
惰性验证配置:配置 = 线 [配置]

错误:找不到公共构造函数或伴生对象 [play.api.libs.ws.WSClient] 懒惰的 val wsc: WSClient = wire[WSClient]

有人知道我该如何解决这个问题...?为什么会这样:/

谢谢!

【问题讨论】:

标签: java scala dependency-injection playframework macwire


【解决方案1】:

Configuration 是一个 playframework 配置,其中internally uses Typesafe 的Config library。引用Playframework docs:

Play使用的配置文件基于Typesafe config library

您得到的异常确切地告诉您这一点 - macwire 无法创建 Configuration 的实例,因为范围内没有 Config 实例。

要修复它,您显然需要提供这样的实例。最简单的方法可能如下所示:

import com.typesafe.config.{Config, ConfigFactory}
trait ApiDependencies {
    lazy val configuration: Config = ConfigFactory.load()
    lazy val conf: Configuration = wire[Configuration]
}

请注意,ConfigFactory.Load() 基本上使用默认配置文件 (application.conf),它确实考虑了 Play's Configuration docs 中描述的配置覆盖技术,因为它实际上是由类型安全配置库 (来自 Typesafe Config GitHub 自述文件):

用户可以使用 Java 系统属性覆盖配置,java -Dmyapp.foo.bar=10


关于WSClient:这是因为WSClient 不是一个类,而是a trait。您需要连接实际的实现,即NingWSClient,如下所示:

trait ApiDependencies {
  lazy val conf: Configuration = wire[Configuration]
  lazy val wsc: WSClient = wire[NingWSClient]
}

请参阅WSClient scaladoc 以获取实现类的列表(在“所有已知的实现类”下) - 在撰写本文时只有NingWSClientAhcWSClient。哪个更好是一个不同的问题(并且可能是基于意见的问题)。

【讨论】:

  • 你有 WSClient 错误的答案吗……也得到了这个:/ @J0HN
  • @JohnBigs 我已经更新了答案 - 请看一下,如果有帮助,请告诉我
猜你喜欢
  • 2012-08-20
  • 1970-01-01
  • 2023-03-03
  • 2021-11-14
  • 2011-12-30
  • 2018-08-28
  • 2012-12-31
  • 2021-12-09
  • 1970-01-01
相关资源
最近更新 更多