使用“环境变量”的TypeSafe Config覆盖值有效,但“系统属性”无效

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

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

无论是通过环境还是通过Java系统属性(-DXXX =)传递ENV_VAR,此代码似乎都遵循foo = ${?ENV_VAR}覆盖语法。

使用.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()的行为略有不同。

还是我只是想念什么?

bm1128 回答:使用“环境变量”的TypeSafe Config覆盖值有效,但“系统属性”无效

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

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

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

是的!

本文链接:https://www.f2er.com/3025814.html

大家都在问