问题
Is there a way for me to dynamically load a setting value from a properties file?
I mean, instead of hardcoding into build.sbt
name := "helloWorld"
Have some application.properties
file with
name=helloWorld
And then, in the build.sbt
file, have name := application.properties["name"]
(last example is purely schematic, but I hope the idea was clear)
回答1:
You can create a setting key which holds properties read from a file.
import java.util.Properties
val appProperties = settingKey[Properties]("The application properties")
appProperties := {
val prop = new Properties()
IO.load(prop, new File("application.properties"))
prop
}
name := appProperties.value.getProperty("name")
回答2:
Cheating a bit on the answer from @daniel-olszewski.
In project/build.sbt
declare dependency on Typesafe Config:
libraryDependencies += "com.typesafe" % "config" % "1.2.1"
In build.sbt
load properties using Typesafe Config and set settings:
import com.typesafe.config.{ConfigFactory, Config}
lazy val appProperties = settingKey[Config]("The application properties")
appProperties := {
ConfigFactory.load()
}
name := {
try {
appProperties.value.getString("name")
} catch {
case _: Exception => "<empty>"
}
}
You could define a def
that would set values from the properties, too.
来源:https://stackoverflow.com/questions/25665848/how-to-load-setting-values-from-a-java-properties-file