scala中用implicit实现依赖注入

import scala.collection.mutable


/**
 * Created by xiaojun on 2015/2/17.
 */
object ScalaDemo extends App {


  case class User(userId: Int, userName: String)

  class UserDao {
    var users = mutable.HashMap((1, User(1, "aaa")), (2, User(2, "bbb")), (3, User(3, "ccc")))

    def findById(userId: Int) = users.get(userId)

    def findAll() = users

    def updateById(u: User) = users.update(u.userId, u)

  }

  implicit val userDao = new UserDao


  class UserService(implicit dao: UserDao) {
    def getAllUsers() = dao.findAll()

    def updateUser(u: User) = dao.updateById(u)
  }
  //这里构造函数不需要传入UserDao的实例,会自动将上面定义的userDao注入到UserService实例中
  val service = new UserService

  println(service.getAllUsers())

  //更新users中userid=1的元组
  service.updateUser(User(1, "AAA"))
  println(service.getAllUsers())

  //新建一个UserService实例service2,打印它可以看到和service打印的users集合石一致的,说明他们用的是同一个userDao实例
  val service2 = new UserService
  println(service2.getAllUsers())

}

你可能感兴趣的:(scala中用implicit实现依赖注入)