从build.sbt和应用程序代码

时间:2018-02-14 08:27:01

标签: scala sbt

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

例如, build.sbt

propName := "hello"

MyApp.scala

buildSbtProvider.getVariable("propName")

或者 build.sbt

propName := CommonObject.hello

MyApp.scala

propName = CommonObject.hello

2 个答案:

答案 0 :(得分:4)

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

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

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

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

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)
}

您可以参考项目的README文件了解更多详情。

答案 1 :(得分:3)

可能使用默认的src/main/resources/application.conf文件。此文件通常用于在运行时设置应用程序的属性。刚发现你可以从build.sbt中读到它(见answer

所以,让我们说这个application.conf有这样的内容:

{ name=my_app_name }

然后你可以从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")

在应用程序方面,这是非常经典的:

import com.typesafe.config.ConfigFactory

var conf = ConfigFactory.load

println(conf.getString("name"))