找不到参数消息的隐式值:play.api.i18n.Messages

问题描述:

我有以下一段代码

import play.api.i18n.{MessagesApi, Messages, I18nSupport}
import play.api.libs.json.Json

case class HttpMessage(key: String, message: String)

object HttpMessage {
  implicit val jsonFormat = Json.format[HttpMessage]

  def apply(key: String): HttpMessage = {
    HttpMessage(key, Messages(key))
  }
}

编译后会抛出

[error] could not find implicit value for parameter messages: play.api.i18n.Messages
[error]     HttpMessage(key, messages(key))
[error]                              ^

我进行了一些研究,似乎找不到MessagesAPIimplicit值.似乎必须像在控制器中那样进行注入,但是我不知道如何进行操作,因为我在这里面临着objectcase class. @Inject注释不被接受.

I made some research and it seems that it cannot find an implicit value for MessagesAPI. It seems it must be inject like in controllers but I do not know how because I am facing an object and case class here. @Inject annotation is not accepted.

我该如何解决?

来自 https://stackoverflow.com/a/30843682的方法/4496364 :

import play.api.Play.current import play.api.i18n.Messages.Implicits._

import play.api.Play.current import play.api.i18n.Messages.Implicits._

不建议使用第一行,因为Play现在在所有可能的地方都使用DI.

The first line is deprecated since Play now uses DI everywhere possible.

我的方法(不能说是好是坏):

My approach (can't say if good or bad):

case class HttpMessage(key: String, message: String)

object HttpMessage {
  implicit val jsonFormat = Json.format[HttpMessage]

  def apply(key: String)(implicit messages: Messages): HttpMessage = {
    HttpMessage(key, Messages(key))
  }
}

我必须创建类似的解决方案,因此我使用了隐式方式,Play也在其模板中使用了隐式方式.您的控制器中必须有implicit request才能起作用.另外,在所有类似服务的类中,您都需要转发此implicit messages: Messages ...

I had to create similar solution, so I used the implicit way, which Play uses also in it's templates. You must have implicit request in your controller for this to work. Also, in all service-like classes you need to forward this implicit messages: Messages...