Search code examples
javaplayframework-2.0sbtsbt-buildinfo

How to access SBT settings from Java code in PlayFramework?


I have a PlayFramework application, and there is a name and version in the build.sbt.

If I run the play console, I can access this information by typing name or version.

How can I get this information from Java code inside the application? I can't seem to find any useful methods in Play.application() and I have not been able to find this in the documentation.


Solution

  • For this you can use the SBT plugin BuildInfo:

    Add to project/plugins.sbt:

    addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.2.5")
    

    And to build.sbt:

    buildInfoSettings
    
    sourceGenerators in Compile <+= buildInfo
    
    buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion)
    
    buildInfoPackage := "hello"
    

    Now you can access the build information with static methods:

    package controllers;
    
    import play.*;
    import play.mvc.*;
    
    import views.html.*;
    
    public class Application extends Controller {
    
        public static Result index() {
            return ok(hello.BuildInfo.name());//the name of the application as output
        }
    
    }