如何在Scala Play中执行启动代码!框架应用? [英] How to execute on start code in scala Play! framework application?

查看:95
本文介绍了如何在Scala Play中执行启动代码!框架应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一个允许在应用程序启动时启动预定作业的代码,我该怎么办?谢谢.

I need to execute a code allowing the launch of scheduled jobs on start of the application, how can I do this? Thanks.

推荐答案

使用 Global 对象(如果使用的话)必须在默认包中定义:

Use the Global object which - if used - must be defined in the default package:

object Global extends play.api.GlobalSettings {

  override def onStart(app: play.api.Application) {
    ...
  }

}

请记住,在开发模式下,该应用仅在第一个请求上加载,因此您必须触发一个请求才能启动该过程.

Remember that in development mode, the app only loads on the first request, so you must trigger a request to start the process.

自Play Framework 2.6x起

执行此操作的正确方法是使用具有预先绑定功能的自定义模块:

The correct way to do this is to use a custom module with eager binding:

import scala.concurrent.Future
import javax.inject._
import play.api.inject.ApplicationLifecycle

// This creates an `ApplicationStart` object once at start-up and registers hook for shut-down.
@Singleton
class ApplicationStart @Inject() (lifecycle: ApplicationLifecycle) {

  // Start up code here

  // Shut-down hook
  lifecycle.addStopHook { () =>
    Future.successful(())
  }
  //...
}

import com.google.inject.AbstractModule

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

请参见 https://www.playframework.com/documentation/2.6.x/ScalaDependencyInjection#Eager-bindings

这篇关于如何在Scala Play中执行启动代码!框架应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆