你问这个是对的,因为它可以大大简化测试。诀窍是使用@Provides 注解:
TL;DR
class MyController @Inject() (byId: (UserId) => Option[User]) extends Controller { ... }
@Provides
def userDao(aDependency: Any): UserDao = // return UserDao, note aDependency will be injected
@Provides
def byId: (UserId) => Option[User] = userDao.byId // note: this method will call the other @Provides method 'userDao'
说明
最终byId: (UserId) => Option[User] 转换为scala.Function1[UserId, Option[User]] 但是您可以使用语法糖声明函数依赖关系:
class MyController @Inject() (_addTwo: (Int, Int) => Int) extends Controller {
def addTwo(a: Int, b: Int) = Action {
Ok(_addTwo(a, b).toString) // call the injected function
}
}
然后在你的 Module.scala 中创建一个返回函数的方法:
@Provides
def addTwo: (Int, Int) => Int = (a, b) => a + b
您可以在 @Provides 方法中执行所有常见的 Scala 操作,例如返回一个部分应用的函数:
@Provides
def addTwo: (Int, Int) => Int = addThree(0, _:Int, _:Int)
def addThree(a: Int, b: Int, c: Int): Int = a + b + c
为避免冲突,您还可以使用@Named 注解:
class MyController @Inject() (@Named("addTwo") _addTwo: (Int, Int) => Int,
@Named("subtractTwo") _subTwo: (Int, Int) => Int)
extends Controller { ... }
@Provides
@Named("addTwo")
def addTwo: (Int, Int) => Int = (a, b) => a + b
@Provides
@Named("subtractTwo")
def subTwo: (Int, Int) => Int = (a, b) => a - b