How do I create a global object/variable in Play Framework 2.0 using Scala?
I want to create a object that once instantiated, can persist between multiple controller actions so that different actions can still call on the same object (because initializing the object is very expensive).
Is this possible without storing it into the DB? I tried sticking the object into a the Global object for the onStart method as shown here:
http://www.playframework.org/documentation/2.0/ScalaGlobal
This was my code:
(in the root application folder)
object Global extends GlobalSettings {
override def onStart(app:Application) {
var foo = new Foo
}
}
}
And in my controller actions I try just calling the variable by name, but it didn't work.
If your globals also need to be available to the methods in Global
, put them in Global.scala like so:
package object globals {
lazy val abc = Play.maybeApplication.flatMap(_.configuration.getString("abc")).getOrElse("default_value_of_abc")
lazy val someActor = Akka.system.actorOf(Props[SomeActor], name = "someActor")
}
And then use it in your controllers like this:
println(globals.abc)
globals.someActor ! SomeMessage
UPDATE
The documentation has since been updated how add Global.scala
in an idiomatic Play! way, with docs for both Scala and Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With