播放2.5依赖注入以进行播放式数据库配置

时间:2016-10-19 21:25:09

标签: mysql scala playframework slick play-slick

我正在尝试使用play-slick插件与mySQL数据库进行交互。除了每次编译代码时得到的[warn],一切都按预期工作。

在这一行:val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)

警告是:method current in object Play is deprecated: This is a static reference to application, use DI instead

我尝试通过使用依赖注入定义Configuration来添加inject()方法,但它不起作用!如何在以下代码中使用Dependency Injection,以便我不必使用自Play.current以来已弃用的Play 2.5

import play.api.Play
import play.api.db.slick.DatabaseConfigProvider
import scala.concurrent.Future
import slick.driver.JdbcProfile
import slick.driver.MySQLDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global


case class User(
    id: Long, 
    firstName: String, 
    lastName: String, 
    mobile: Long, 
    email: String
)

class UserTableDef(tag: Tag) extends Table[User](tag, "users") {

  def id = column[Long]("id", O.PrimaryKey,O.AutoInc)
  def firstName = column[String]("first_name")
  def lastName = column[String]("last_name")
  def mobile = column[Long]("mobile")
  def email = column[String]("email")

  override def * =
    (id, firstName, lastName, mobile, email) <>(User.tupled, User.unapply)
}

object Users {

  val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current) //<-- PROBLEM

  val users = TableQuery[UserTableDef]

  def get(id: Long): Future[Option[User]] = {
    dbConfig.db.run(users.filter(_.id === id).result.headOption)
  }

}

1 个答案:

答案 0 :(得分:2)

Play current已弃用。 DBConfigProvider将使用guice注入。

DatabaseConfigProvider将使用guice依赖注入注入到类UsersRepo中。

以下是使用Guice和Play 2.5

执行此操作的方法
case class User(profileName: ProfileName,
                email: Email,
                createdAt: DateTime,
                id: UserId)

@Singleton
class UsersRepo @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) {
  val dbConfig = dbConfigProvider.get[JdbcProfile]

  import dbConfig.driver.api._

  private[services] val users = TableQuery[Users]

  def exists(id: UserId): DBIO[Boolean] = {
    users.filter(_.id === id).exists.result
  }


  private[services] class Users(tag: Tag) extends Table[User](tag, UsersTable.name) {
    def profileName = column[ProfileName]("profile_name")

    def id = column[UserId]("user_id", O.PrimaryKey)

    def email = column[Email]("email")

    def createdAt = column[DateTime]("created_at")

    def * = (profileName, email, source, createdAt, id) <> (User.tupled, User.unapply)

    def emailIndex = index("users_email_index", email, true)
  }

}

在application.conf

中使用play-slick时的数据库配置
slick.dbs.default.driver="slick.driver.PostgresDriver$"
slick.dbs.default.db.driver="org.postgresql.Driver"
slick.dbs.default.db.url="jdbc:postgresql://ec2-54-217-243-228.eu-west-1.compute.amazonaws.com:5432/d344onl0761ji5?user=user&password=pass"
slick.dbs.default.db.user=user
slick.dbs.default.db.password="pass"