I need to access a build.sbt
variable from application code, or define some class/object accessible both from the build.sbt
and the application code. How to do this?
For example,
build.sbt
:
propName := "hello"
MyApp.scala
:
buildSbtProvider.getVariable("propName")
Or
build.sbt
:
propName := CommonObject.hello
MyApp.scala
:
propName = CommonObject.hello
You may want to use the sbt-buildinfo
plugin for this.
As stated in the documentation, you just have to add a few definition to your build
lazy val root = (project in file(".")).
enablePlugins(BuildInfoPlugin).
settings(
buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion),
buildInfoPackage := "hello"
)
And this would generate the following class that you can use after reload:
package hello
import java.io.File
import java.lang._
import java.net.URL
import scala._; import Predef._
/** This object was generated by sbt-buildinfo. */
case object BuildInfo {
/** The value is "helloworld". */
val name: String = "helloworld"
/** The value is "0.1-SNAPSHOT". */
val version: String = "0.1-SNAPSHOT"
/** The value is "2.10.3". */
val scalaVersion: String = "2.10.3"
/** The value is "0.13.2". */
val sbtVersion: String = "0.13.2"
override val toString: String = "name: %s, version: %s, scalaVersion: %s, sbtVersion: %s" format (name, version, scalaVersion, sbtVersion)
}
You can refer to the README file of the project for more details.
A possibility would be to use the default src/main/resources/application.conf
file. This file is often used to set properties for the application at run time. And just discovered you can read it from build.sbt (see this answer)
So let's say this application.conf has this content:
{ name=my_app_name }
Then you can get the name from within build.sbt:
import java.util.Properties
val appProperties = settingKey[Properties]("The application properties")
appProperties := {
val prop = new Properties()
IO.load(prop, new File("src/main/resources/application.conf"))
prop
}
name := appProperties.value.getProperty("name")
On the application side, this is very classic:
import com.typesafe.config.ConfigFactory
var conf = ConfigFactory.load
println(conf.getString("name"))
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