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.
Best Answer
If your globals also need to be available to the methods in
Global
, put them in Global.scala like so:And then use it in your controllers like this:
UPDATE
The documentation has since been updated how add
Global.scala
in an idiomatic Play! way, with docs for both Scala and Java.