【问题标题】:How to inject a trait with macwire如何使用 macwire 注入特征
【发布时间】:2016-06-10 19:03:36
【问题描述】:

我有一个 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

【问题讨论】:

    标签: scala macwire


    【解决方案1】:

    您可以尝试将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
    }
    

    【讨论】:

    • 谢谢,这就是我要找的。​​span>
    猜你喜欢
    • 2019-11-22
    • 2015-03-08
    • 2017-12-06
    • 1970-01-01
    • 2018-06-04
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多