从build.sbt和应用程序代码访问对象

Igo*_*ock 3 scala sbt

我需要build.sbt从应用程序代码访问变量,或者定义一些可以从build.sbt和应用程序代码访问的类/对象。这该怎么做?

例如 build.sbt

propName := "hello"
Run Code Online (Sandbox Code Playgroud)

MyApp.scala

buildSbtProvider.getVariable("propName")
Run Code Online (Sandbox Code Playgroud)

build.sbt

propName := CommonObject.hello
Run Code Online (Sandbox Code Playgroud)

MyApp.scala

propName = CommonObject.hello
Run Code Online (Sandbox Code Playgroud)

ste*_*ino 5

您可能要为此使用sbt-buildinfo插件。

如文档中所述,您只需要在构建中添加一些定义即可

lazy val root = (project in file(".")).
  enablePlugins(BuildInfoPlugin).
  settings(
    buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion),
    buildInfoPackage := "hello"
  )
Run Code Online (Sandbox Code Playgroud)

这将生成以下类,可在重新加载后使用:

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)
}
Run Code Online (Sandbox Code Playgroud)

您可以参考项目的自述文件以了解更多详细信息。