如何 运行 在 Play! 启动时编写代码!框架 2.4

How to run code on startup in Play! framework 2.4

我正在尝试在应用程序启动时打印 "Hello" 到控制台。你能解释一下怎么做吗?

我自己尝试过的:

app/modules/HelloModule.scala:

package modules

import com.google.inject.AbstractModule

trait Hello {}

class MyHelloClass extends Hello {
  initialize() // running initialization in constructor
  def initialize() = {
    println("Hello")
  }
}

class HelloModule extends AbstractModule {
  def configure() = {
    bind(classOf[Hello])
      .to(classOf[MyHelloClass]).asEagerSingleton
  }
}

conf/application.conf 我补充说:

play.modules.enabled += "modules.HelloModule"
当 i 运行 activator run

和 "Hello" 不打印

您需要使用 Global object,并覆盖 "onStart" 方法:

Defining a Global object in your project allows you to handle global settings for your application. This object must be defined in the default (empty) package and must extend GlobalSettings.

import play.api._

object Global extends GlobalSettings {

  override def onStart(app: Application) {
    Logger.info("Application has started")
  }

  override def onStop(app: Application) {
    Logger.info("Application shutdown...")
  }

}

You can also specify a custom GlobalSettings implementation class name using the application.global configuration key.

更新:

正确的方法是使用依赖注入,就像问题中描述的那样。 GlobalSettings could be removed later

题目中的代码没有问题。我在我的本地设置上验证了它。在开发模式 "activator run" 中首次请求后和在生产模式 "activator start" 中启动应用程序后,代码写入 "Hello"。

顺便说一句,尝试使用一些更容易在日志中找到的字符串,比如

"--------APP DZIABLO 已启动--------"

可能是你在日志中漏掉了"Hello"(我一开始没认出来)