我试图使用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。
我已经尝试过通过使用依赖注入定义配置来添加inject()方法,但是它不起作用!如何在下面的代码中使用Dependency Injection,这样我就不必使用自Play 2.5以来就不再推荐的Play.current了
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)
}
}发布于 2016-10-20 03:00:57
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)
}
}在play-slick中使用application.conf时的DB配置
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"https://stackoverflow.com/questions/40141762
复制相似问题