Play Framework 2: Read the application version defined in Build.scala

You can get the current version of Play by using:

play.core.PlayVersion.current();

You can define the version in application.conf and let Build.scala read the value. I did this with the version number and application name. The following works in Play 2.0, there is an updated solution for Play 2.1.

In project/Build.scala, load the configuration and get the properties:

val conf = play.api.Configuration.load(new File("."))
val appName    = conf.getString("app.name").getOrElse("unnamed application")
val appVersion = conf.getString("app.version").getOrElse("0.0.0")

In conf/application.conf define the properties:

app.version = 1.0
app.name = My Application

Finally in your application it will be accessible with

 Play.application().configuration().getString("app.version")

The configuration syntax has quite some features, so you can even go a little more crazy with your version or application names:

app {
  major    = 1
  minor    = 2
  revision = 3
  version = ${app.major}.${app.minor}.${app.revision}
  name = My Application ${app.major}.${app.minor}
}

I use the SBT BuildInfo plugin for this purpose:

import sbtbuildinfo.Plugin._

val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA, settings = Defaults.defaultSettings ++ buildInfoSettings).settings(

  buildInfoKeys := Seq[Scoped](name, appVersion, scalaVersion, sbtVersion),
  buildInfoPackage := "org.foo.bar",

  ...

)

This generates an org.foo.bar.BuildInfo object which you can then call from the source code:

org.foo.bar.BuildInfo.version

You can also define custom keys in the build and add them to the buildInfoKeys, which is quite useful if your build gets more complex.


This is how you can get Play application version and application name defined in your build.sbt

name := "myApp"
version :="1.0.4" 

Notice this only works in PROD mode. In dev mode SBT shares a JVM instance with the application and those calls return something different.

Application.class.getPackage().getImplementationTitle());     // returns "myApp"
Application.class.getPackage().getImplementationVersion());    // returns "1.0.4"

In this case Application class is a class defined in your project. It can be any class from your project.

UPDATE

I noticed that this method doesn't work out of the box for Play >=2.4.x

To fix the problem add this to your build.sbt

packageOptions += Package.ManifestAttributes(
  "Implementation-Version" -> (version in ThisBuild).value,
  "Implementation-Title" -> name.value
)

The two properties will be appended to MANIFEST.FM file in your build so the package title and version can be read from the code.

fyi: I use SBT native packager

addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.0.3")