当我从字符串解析配置时,我可以解析替换,但在从映射或文件解析时不能解析。
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}"}))
我也许可以将map/文件转换成字符串,但是有办法让库来处理它吗?
发布于 2017-03-21 11:48:26
ConfigFactory.parseMap
方法导致fromAnyRef
,对我们来说相关的部分是:
if (object instanceof String)
return new ConfigString.Quoted(origin, (String) object);
它从不将值解析为ConfigReference
,因此resolve
无法工作。
他们的基本原理可能是,如果您“控制”数据结构,那么您就可以利用scala字符串内插。
对于parseFile
来说,情况要简单一些。Java文件不支持${}
替换,文件的类型由(.properties
)文件扩展名猜测。
例如,您可以使用HOCON
格式:您只需重命名文件(例如,test.conf
),然后${}
替换就可以开箱即用。
这里有更多信息:霍康
https://stackoverflow.com/questions/42903899
复制相似问题