How to load setting values from a Java properties file?

纵饮孤独 提交于 2019-12-22 04:05:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!