在Play 2.5.X中,我们需要使用依赖注入。下面的代码是从游戏的文档的例子:在Play中创建依赖注入类的实例2.5.X
class HomeController @Inject() (configuration: play.api.Configuration) extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
}
如果我定义了一些额外的helper方法getXXX
在HomeController
,需要从别的地方访问它,我怎么可以访问此方法?
我真正感兴趣的是如何创建HomeController
的实例,以便我可以使用homeControllerInstance.getXXX
。
如果我试图像下面创建实例:
val homeControllerInstance = new HomeController()
我得到错误:
Compilation error[not enough arguments for constructor HomeController: (configuration: play.api.Configuration)HomeController
我试图改变HomeController
类声明:
class HomeController @Inject(configuration: play.api.Configuration) extends Controller
但是这给了我错误:
classfile annotation arguments have to be supplied as named arguments
有人能解释一下,我该如何解决这个问题?
这个辅助方法是什么?你确定控制器是最好的地方吗? – michaJlS
你的问题不是很清楚。你在问如何将控制器声明为可注入组件? – Nio
这是单元测试吗?如果是这种情况,您可能需要查看指南https://www.playframework.com/documentation/2.5.x/ScalaTestingWithGuice –