Scala:将值写入类型安全的配置对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24153614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:19:47  来源:igfitidea点击:

Scala: Write value to typesafe config object

scalatypesafe-config

提问by goo

I'm using Typesafe config & have a config file in my resources directory which looks like this:

我正在使用 Typesafe 配置并在我的资源目录中有一个配置文件,如下所示:

something {
  another {
    someconfig=abc
    anotherconfig=123
  }
}

How would I change the value of anotherconfigusing scala?

我将如何改变anotherconfig使用 scala的价值?

回答by Christian

If you want to change the loaded config (i.e. create a new config based on the old one), you can use withValue:

如果要更改加载的配置(即基于旧配置创建新配置),可以使用 withValue:

val newConfig = oldConfig.withValue("something.another.anotherconfig",
  ConfigValueFactory.fromAnyRef(456))

回答by Mario Camou

You can't overwrite a value in the original Config object since it's immutable. What you can do is create a new Config object with your values, using the original as a fallback. So:

您不能覆盖原始 Config 对象中的值,因为它是不可变的。您可以做的是使用您的值创建一个新的 Config 对象,使用原始值作为后备。所以:

val myConfig = ConfigFactory.parseString("something.another.anotherconfig=456")
val newConfig = myConfig.withFallback(oldConfig)

and then use newConfig everywhere instead of your original Config. A more maintainable option would be to have a 2nd config file with your changes and use:

然后在任何地方使用 newConfig 而不是你原来的 Config。一个更易于维护的选项是使用第二个配置文件进行更改并使用:

val myConfig = ConfigFactory.load("local")
val oldConfig = ConfigFactory.load
val realConfig = myConfig.withFallback(oldConfig)

You could then use a System Property to set where to load myConfigfrom.

然后,您可以使用系统属性来设置myConfig从何处加载。