首页 > 解决方案 > TypeSafe Config 使用环境变量覆盖值有效,系统属性不起作用,当

问题描述

我有一个使用 TypeSafe 配置的项目。它加载多个配置文件。一种是加载简单的方法:

private val config = ConfigFactory.load( "test-parameters" )

这似乎尊重foo = ${?ENV_VAR}覆盖语法,无论 ENV_VAR 是通过环境还是通过 Java 系统属性 (-DXXX=) 传入的。

其他配置文件使用.parseResources()后跟一个最终的.resolve(). 如果将变量指定为环境变量,则覆盖语法可以正常工作,但是当它们是系统属性时不会发生任何事情。代码如下所示:

// we define a layered config, so that you can define values in one layer, and customize them in another
// if your environment includes sub-folders, config files are read from deepest folder first
// so that you can define values in the higher folders and override them in the more specific folder
// e.g. if the environment is "foo/bar/baz", then the order of loading config files is:
//  * application.conf
//  * conf/foo/bar/baz/config.conf
//  * conf/foo/bar/config.conf
//  * conf/foo/config.conf
//  * default.conf
def loadConfig(env: String): Config = {
  // do not allow the user to supply a relative path that tries to escape the conf directory hierarchy
  if (env != null && env.matches("(?:^|/)\\.\\./"))
    throw new Exception("Illegal Environment String")

  var c = userConfig
  if (env != null && env != "") {
    val parts = env.split("/")
    var n = parts.length
    while (n > 0) {
      c = c.withFallback(ConfigFactory.parseResources(environmentConfigFile(parts.take(n).mkString("/"))))
      n -= 1
    }
  }
  c.withFallback(defaultConfig).resolve()
}
def loadConfig: Config = loadConfig(Test.environment)

乍一看,它看起来像一个错误。 .parseResources().resolve()并且.load()行为略有不同。

还是我只是错过了什么?

标签: typesafe-config

解决方案


问题是缺少ConfigFactory.load(),它会自动合并到系统属性中。

通过更改初始化,如下所示,它按预期工作:

var c = ConfigFactory.load().withFallback( userConfig )

耶!


推荐阅读