ProvisionException:类必须具有一个(且只有一个)使用@Inject注释的构造函数或零参数

时间:2017-07-04 13:00:50

标签: scala playframework guice playframework-2.4

我在PlayFramework中使用Guice但是我遇到了运行时错误:

Caused by: com.google.inject.ProvisionException: Unable to provision, see the following errors:

1) Could not find a suitable constructor in controllers.DirectUserController. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
  at controllers.DirectUserController.class(DirectUserController.scala:90)
  while locating com.google.inject.Provider<controllers.DirectUserController>
    for parameter 7 at router.Routes.<init>(Routes.scala:124)
  while locating router.Routes
  while locating play.api.inject.RoutesProvider
  while locating play.api.routing.Router

1 error
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1025) ~[guice-4.0.jar:na]
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051) ~[guice-4.0.jar:na]
    at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:321) ~[play_2.11-2.4.3.jar:2.4.3]
    at play.api.inject.guice.GuiceInjector.instanceOf(GuiceInjectorBuilder.scala:316) ~[play_2.11-2.4.3.jar:2.4.3]
    at play.api.Application$class.routes(Application.scala:111) ~[play_2.11-2.4.3.jar:2.4.3]

以下是代码:

trait FactoryHandlerTrait {
  def getDirectUserFactory: DirectUserFactory

  def getUserRepository: UserRepository

  def getUrlRepository: URLRepository
}

class FactoryHandler(var s: String = "real") extends FactoryHandlerTrait {
  def getDirectUserFactory: DirectUserFactory = {
    //implementation here
  }

  def getUserRepository: UserRepository = {
    //implementation here
  }

  def getUrlRepository: URLRepository = {
    //implementation here
  }
}

class DependencyModule extends Module {

  def configure(binder: Binder) = {
    binder.bind(classOf[FactoryHandlerTrait]).to(classOf[FactoryHandler])
  }
}

这是我的控制器:

class DirectUserController(var factory:FactoryHandlerTrait) extends Controller {  
  //rest of the code
}

build.sbt我已添加:

routesGenerator := InjectedRoutesGenerator

我错过了什么或做错了什么?如何避免这种异常?

我正在使用Play 2.4.3和Guice 3.0。

1 个答案:

答案 0 :(得分:2)

正如guice所说,构造函数必须具有零参数,或者您需要使用@Inject对其进行注释。您的班级FactoryHandler并未满足这些要求。

在解决此问题时,您可能想要考虑参数s是否实际上是可以由guice注入的参数(可能不是)。因此,您需要以其他方式传递它。如果它仅在运行时可用,您可能需要查看辅助注入。我在之前的回答中描述了它的工作原理:https://stackoverflow.com/a/35960962/1080523