![](/img/trans.png)
[英]Play Framework 2.2 dependancies not downloading where I expect them to
[英]Fail to wire play dependancies with Macwire
我有一個api服務類,它依賴於播放的Configuration和WSClient實例。
而且我不想使用@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]
惰性val conf:配置= wire [配置]錯誤:無法為[play.api.libs.ws.WSClient]惰性val wsc找到公共構造函數或伴隨對象:WSClient = wire [WSClient]
有人知道我該如何解決這個問題...? 以及為什么會這樣:/
謝謝!
Configuration
是一個播放框架配置,在內部使用 Typesafe的Config庫 。 引用Playframework文檔 :
Play使用的配置文件基於Typesafe配置庫
您所獲得的異常恰好告訴您這一點-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的Configuration文檔中描述的配置替代技術,因為它實際上是由typesafe配置庫提供的(來自Typesafe Config GitHub自述文件):
用戶可以使用Java系統屬性java -Dmyapp.foo.bar = 10覆蓋配置。
關於WSClient
:這是由於WSClient
不是類,而是trait 。 您需要連接實際的實現,即NingWSClient
,如下所示:
trait ApiDependencies {
lazy val conf: Configuration = wire[Configuration]
lazy val wsc: WSClient = wire[NingWSClient]
}
有關實現類的列表,請參閱WSClient
scaladoc(在“所有已知的實現類”下)-在撰寫本文時,只有NingWSClient
和AhcWSClient
。 哪個更好是一個不同的問題(可能是基於觀點的問題)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.