10

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)

2 Answers 2

14

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")
8

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.

1
  • I tried this approach but apparently the config then is empty. If I do the same in my application it works fine.
    – Hannes
    Apr 2, 2020 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.