typesafe config
https://github.com/lightbend/config
config loading library created by typesafe (now lightbend)
――I used it somehow, so I wrote it to organize it. --I use it in Scala
--Setting library written in java without dependent libraries --You can read the configuration file written in JSON (.json) or HOCON (.conf) into the application.
Let's write in build.sbt
libraryDependencies += "com.typesafe" % "config" % "1.3.1"
Load the config file with ConfigFactory.load
.
You can get the value from the key set from the returned config object and use it.
The Config object has a method of get ~
, and you can read what you wrote in the config file by specifying the type. When reading, an error will occur if the method and the actual value type are different
The code becomes ↓
import com.typesafe.config.ConfigFactory
object ConfigSample {
def main(args: Array[String]): Unit = {
val config: Config = ConfigFactory.load()
config.get~("path") //Set value~Use as a mold to read
// String, Int, Enum, Boolean, etc...
val subconf: Config = config.getConfig("subconfig")
//When there is a conf file like the one below
//A Config object rooted in subconfig is returned in subconf
//So`subconf.getString("host")`Then"sub_host"Returns
/*
* # application.conf
* host = "main_host"
* subconfig {
* host = "sub_host"
* }
*/
}
}
File path config contents
ConfigFactory.load("file name") // file nameには拡張子を含めない
ʻapplication.conf, ʻapplication.json
, ʻapplication.properties,
reference.conf` and system properties under src / main / resources
application.conf
> application.json
> application.properties
> reference.conf
The set value is prioritized with
Since reference.conf is read later, it seems good to write the default value when creating a library.
include
--If it is a conf file, the settings of the file specified by ʻinclude" file name " can also be imported into the file in which ʻinclude
is written. If the file that has been included
and thefile that has been
have the same key setting value, the setting value on theside
has priority.
--The file to include does not have to be a conf file (json, properties are OK)
a.conf
a = "a"
application.conf
include "a"
b = "b"
val config = ConfigFactory.load()
config.getString("a") // a
config.getString("b") // b
Property name = $ {replacement source property name}
application_host = "untarakantara.com"
application_url = "https://${application_host}"
ConfigFactory.load().getString("application_url") // `https://untarakantara.com`
Property name = $ {? Environment variable}
If there is no environment variable and a value with the same property name as the environment variable name is set in conf, it will be used.
password = ${?PASS_WORD}
Recommended Posts