我正在使用 scala play 2.5,并且在尝试在我的一个 Controller 中注入(inject)一个对象时出现以下错误。
我正在使用 play 提供的默认注入(inject)框架,即 Guice。

    ProvisionException: Unable to provision, see the following errors:
    1) No implementation for services.MyService was bound.
    while locating services.MyService for parameter 0 at controllers.MyController.<init>(MyController.scala:12)
    while locating controllers.MyController for parameter 3 at router.Routes.<init>(Routes.scala:55)
    while locating router.Routes
    while locating play.api.inject.RoutesProvider while locating play.api.routing.Router for parameter 0 at play.api.http.JavaCompatibleHttpRequestHandler.<init>(HttpRequestHandler.scala:200)
    while locating play.api.http.JavaCompatibleHttpRequestHandler
    while locating play.api.http.HttpRequestHandler for parameter 4 at play.api.DefaultApplication.<init>(Application.scala:221) at play.api.DefaultApplication.class(Application.scala:221)
while locating play.api.DefaultApplication
    while locating play.api.Application

这是 Controller :
package controllers

import services.MyService

class MyController @Inject()(myService: MyService, val messagesApi: MessagesApi) extends Controller with I18nSupport {

    def someFunctionThatUsesMyService(url: String) = Action {}
}

这是我想注入(inject)的服务:
package services

import javax.inject._

trait MyService {
    def op(param1: String, param2: String): Boolean
}

@Singleton
class BasicMyService extends MyService {
    override def op(param1: String, param2: String): Boolean = true
}

这就是我使用它的方式:
@Singleton
class HomeController @Inject() extends Controller {

  /**
   * Create an Action to render an HTML page with a welcome message.
   * The configuration in the `routes` file means that this method
   * will be called when the application receives a `GET` request with
   * a path of `/`.
   */
  def index = Action {
    //Ok(views.html.index("Your new application is ready."))
    Redirect(routes.MyController.someFunctionThatUsesMyService(Some(routes.OtherController.welcomePage().url)))
  }

}

最佳答案

您应该将 ImplementedBy 注释添加到 Service trait

package services

import javax.inject._

@ImplementedBy(classOf[BasicMyService])
trait MyService {
    def op(param1: String, param2: String): Boolean
}

@Singleton
class BasicMyService extends MyService {
    override def op(param1: String, param2: String): Boolean = true
}

关于Scala 玩 Guice 注入(inject),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37114732/

10-13 09:25