Play(Scala)类型安全配置中的* Ordered *对象

时间:2018-07-20 19:38:47

标签: scala playframework typesafe-config

如何在Play 2.6.x(Scala)的以下.conf中访问customers排序列表:

customers {
  "cust1" {
    env1 {
      att1: "str1"
      att2: "str2"
    }
    env2 {
      att1: "str3"
      att2: "str5"
    }
    env3 {
      att1: "str2"
      att2: "str6"
    }
    env4 {
      att1: "str1"
      att2: "str2"
    }
  }
  "cust2" {
    env1 {
      att1: "faldfjalfj"
      att2: "reqwrewrqrq"
    }
    env2 {
      att1: "falalfj"
      att2: "reqwrrq"
    }
  }
  "cust3" {
    env3 {
      att1: "xvcbzxbv"
      att2: "hello"
    }
  }
}

List("cust1", "cust2", "cust3"),在此示例中。

2 个答案:

答案 0 :(得分:1)

class SomeClass @Inject()(config: Configuration) {
  Logger.debug("Customers from config: " + config.underlying.getConfig("customers"))
}

会给你的。

Customers from config: Config(SimpleConfigObject(
    {"cust1":{
        "env1":{"att1":"str1","att2":"str2"},
        "env2":{"att1":"str3","att2":"str5"},
        "env3":{"att1":"str2","att2":"str6"},
        "env4":{"att1":"str1","att2":"str2"}},
    "cust2":{
        "env1":{"att1":"faldfjalfj","att2":"reqwrewrqrq"},
        "env2":{"att1":"falalfj","att2":"reqwrrq"}},
   "cust3":{
        "env3":{"att1":"xvcbzxbv","att2":"hello"}}}))

如果要使用对象,显然必须进行转换。

答案 1 :(得分:1)

以下示例应该起作用:

val config : Configuration = ???
config.getObject("customers").entrySet().asScala.map(_.getKey).toList

修改

如果客户按词典顺序排序,则可以致电.sorted

如果更改配置不会影响已经实施的逻辑,则可以像下面这样重新构造配置:

customers : [
  {
    name : "cust1"
    env1 {
      att1: "str1"
      att2: "str2"
    }
    env2 {
      att1: "str3"
      att2: "str5"
    }
    env3 {
      att1: "str2"
      att2: "str6"
    }
    env4 {
      att1: "str1"
      att2: "str2"
    }
  }
   {
    name : "cust2"
    env1 {
      att1: "faldfjalfj"
      att2: "reqwrewrqrq"
    }
    env2 {
      att1: "falalfj"
      att2: "reqwrrq"
    }
  }
  {
    name: "cust3"
    env3 {
      att1: "xvcbzxbv"
      att2: "hello"
    }
  }
  {
    name : "bob"
    env1 {
      att1: "str1"
      att2: "str2"
    }
    env2 {
      att1: "str3"
      att2: "str5"
    }
    env3 {
      att1: "str2"
      att2: "str6"
    }
    env4 {
      att1: "str1"
      att2: "str2"
    }
  }
  {
    name : "john"
    env1 {
      att1: "faldfjalfj"
      att2: "reqwrewrqrq"
    }
    env2 {
      att1: "falalfj"
      att2: "reqwrrq"
    }
  }
  {
    name: "jack"
    env3 {
      att1: "xvcbzxbv"
      att2: "hello"
    }
  }
]

,使用pureconfig,您可以执行以下操作:

import pureconfig.loadConfigOrThrow

final case class Named(name: String)

loadConfigOrThrow[List[Named]]("customers").map(_.name)