如何在Play Framework中启动应用程序启动数据库?

时间:2017-01-06 06:02:42

标签: playframework

我想在启动期间创建一个调度程序并在数据库中获取cron表达式。但是我收到错误“注入构造函数时出错,java.lang.RuntimeException:没有启动的应用程序”。

我认为问题在于使用play.api.Play.current但我需要它用于DB.withConnection {implicit connection =>

我是否需要注入数据库连接?我怎么做?或者我使用了错误的方法?请指教。

这是我到目前为止所拥有的......

Application.conf

play.modules.enabled += "tasks.MyRecurrentTaskModule"

MyRecurrentTaskModule.scala

class MyRecurrentTaskModule extends AbstractModule {
  override def configure() = {
    bind(classOf[RecurrentTask]).asEagerSingleton()
  }
}

@Singleton
class RecurrentTask @Inject() (actorSystem: ActorSystem, lifecycle: ApplicationLifecycle) {

    lifecycle.addStopHook{ () =>

        Future.successful(actorSystem.shutdown())
    }
    // Error when I access db
    val schedule = models.ScheduleTable.getSchedule(1)
    ...

}

ScheduleTable.scala

import play.api.db._
import play.api.Play.current

case class ScheduleTable (
  ...
) {
}

object ScheduleTable {
val scheduleParser = {
  ...
  }
}

def getSchedule (ScheduleId: Int): Option[ScheduleTable] = {
    DB.withConnection { implicit connection =>
      SQL("""
          select * from SCHEDULE_TABLE s
          where s.ScheduleId = {sid}
          """)
      .on('sid -> ScheduleId)
      .as(ScheduleTable.scheduleParser.singleOpt)
    }
}
...

1 个答案:

答案 0 :(得分:-1)

我现在得到了..首先我需要将我的模型从类(Play 2.5)和Inject DBApi更改为object。顺便说一句,我将它从ScheduleTable重命名为ScheduleTableService以避免错误

<强> ScheduleTable.scala

@javax.inject.Singleton
class ScheduleTableSevice @Inject() (dbapi: DBApi) {

  private val db = dbapi.database("default")

  val scheduleParser = {
    ...
    }
  }

  def getSchedule (ScheduleId: Int): Option[ScheduleTable] = {
    db.withConnection { implicit connection =>
      SQL("""
          select * from SCHEDULE_TABLE s
          where s.ScheduleId = {sid}
          """)
      .on('sid -> ScheduleId)
      .as(scheduleParser.singleOpt)
    }
  }

<强> MyRecurrentTaskModule.scala

然后将其注入MyRecurrentTaskModule.scala

class RecurrentTask @Inject() (actorSystem: ActorSystem, lifecycle: ApplicationLifecycle, scheduleService: TxScheduleSevice) {