我在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。
答案 0 :(得分:2)
正如guice所说,构造函数必须具有零参数,或者您需要使用@Inject
对其进行注释。您的班级FactoryHandler
并未满足这些要求。
在解决此问题时,您可能想要考虑参数s
是否实际上是可以由guice注入的参数(可能不是)。因此,您需要以其他方式传递它。如果它仅在运行时可用,您可能需要查看辅助注入。我在之前的回答中描述了它的工作原理:https://stackoverflow.com/a/35960962/1080523