Search code examples
scalaplayframeworkplayframework-2.4

How to run code on startup in Play! framework 2.4


I im trying to print "Hello" to console on application start. Can You explain how to do it?

What i tried myself:

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
  }
}

in conf/application.conf i added:

play.modules.enabled += "modules.HelloModule"

and "Hello" is not printed when i run activator run


Solution

  • You need to use Global object, and override "onStart" method:

    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.

    Update:

    The correct way would be to use Dependency Injection, exactly like it described in the question. GlobalSettings could be removed later

    There is no problem with the code in the question. I verified it on my local setup. The code write "Hello" after first request in the development mode "activator run" and after application start in the production mode "activator start".

    Btw, try to use some more easy to find string in the log, like

    "--------APP DZIABLO HAS BEEN STARTED--------"

    It could be so you just missed "Hello" in the log (I did not recognise it from the start)

    enter image description here