【问题标题】:Typesafe config - parse from map/file and resolve类型安全配置 - 从地图/文件解析并解析
【发布时间】:2017-03-21 19:59:26
【问题描述】:

当我从字符串解析配置时,我可以解决替换问题,但从映射或文件解析时却不行。

import java.io.File
import com.typesafe.config.{Config, ConfigFactory}
import scala.collection.JavaConversions.mapAsJavaMap

val s: String = "a = test, b = another ${a}"
val m: Map[String, String] = Map("a" -> "test", "b" -> "another ${a}")
val f: File = new File("test.properties") // contains "a = test\nb = another ${a}"

val cs: Config = ConfigFactory.parseString(s).resolve
val cm: Config = ConfigFactory.parseMap(mapAsJavaMap(m)).resolve
val cf: Config = ConfigFactory.parseFile(f).resolve

println("b from string = " + cs.getString("b"))
println("b from map = " + cm.getString("b"))
println("b from file = " + cf.getString("b"))

> b from string = another test
> b from map = another ${a}
> b from file = another ${a}

当我没有立即解决时,可以看出变量占位符并没有真正以同样的方式处理:

val cs: Config = ConfigFactory.parseString(s)
val cm: Config = ConfigFactory.parseMap(mapAsJavaMap(m))
val cf: Config = ConfigFactory.parseFile(f)

> cs: com.typesafe.config.Config = Config(SimpleConfigObject({"a":"test","b":"another "${a}}))
> cm: com.typesafe.config.Config = Config(SimpleConfigObject({"a":"test","b":"another ${a}"}))
> cf: com.typesafe.config.Config = Config(SimpleConfigObject({"a":"test","b":"another ${a}"}))

我可能只是将地图/文件转换为字符串,但有没有办法让库处理它?

【问题讨论】:

  • 在图书馆的Github page 上有一个问题,或多或少问同样的问题,解释类似于下面 Federico 的回答。

标签: scala config typesafe-config


【解决方案1】:

ConfigFactory.parseMap 方法导致fromAnyRef,我们的相关部分是:

if (object instanceof String)
  return new ConfigString.Quoted(origin, (String) object);

它从不将值解析为ConfigReference,因此resolve 无法工作。

他们的理由可能是,如果您“控制”数据结构,那么您可以以某种方式利用 scala 字符串插值。


对于parseFile,情况更容易。 Java 属性文件不支持 ${} 替换,文件类型由 (.properties) 文件扩展名猜测。

例如,您可以只使用HOCON 格式:您只需重命名文件(例如test.conf),然后${} 替换应该可以开箱即用。

更多信息在这里:HOCON

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2011-12-10
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多