[英]How to inject a trait with macwire
我有Scala特质
trait UserRepository {
def findByEmail(email: String): User
}
我想将其注入MacWire服务中
class AccountService(){
val userRepo = wire[UserRepository]
}
然后在测试或课程中使用它
class AccountServiceSpec {
val userRepo = new UserRepositoryImpl()
val accountSvc = new AccountService() //<--not manually injecting repo in service constructor
}
但是我在服务类中遇到了编译错误
找不到accounts.repository.UserRepository的公共构造函数或伴随对象
您可以尝试将userRepo
转换为类参数,该参数允许macwire自动提供其用于服务的值:
import com.softwaremill.macwire._
case class User(email: String)
trait UserRepository {
def findByEmail(email: String): User
}
class AccountService(val userRepo: UserRepository)
class UserRepositoryImpl extends UserRepository{
def findByEmail(email: String): User = new User(email)
}
class AccountServiceSpec {
val userRepo = new UserRepositoryImpl()
val accountSvc = wire[AccountService] //<--not manually injecting repo in service constructor
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.