播放(标量)配置映射对象

时间:2018-07-12 17:47:20

标签: scala playframework configuration typesafe-config

我想访问以下配置

customers {
  "cust1" {
    clientId: "id1"
    attrs {
      att1: "str1"
      att2: "str2"
      att3: "str3"
      att4: "str4"
    }
  }
  "cust2" {
    clientId: "id2"
    attrs: {
      att1: "faldfjalfj"
      att2: "reqwrewrqrq"
    }
  }
  "cust3" {
    clientId: "id3"
    attrs {
      att2: "xvcbzxbv"
    }
  }
}

Map[String, CustomerConfig],其中CustomerConfig

package models

import play.api.ConfigLoader
import com.typesafe.config.Config // I added this import in order to make the documentation snippet compile to the best of my knowledge.

case class CustomerConfig(clientId: String, attrs: Map[String, String])

object CustomerConfig {
  implicit val configLoader: ConfigLoader[CustomerConfig] = new ConfigLoader[CustomerConfig] {
  def load(rootConfig: Config, path: String): CustomerConfig = {
    val config = rootConfig.getConfig(path)
    CustomerConfig(
      clientId = config.getString("clientId"),
      attrs = config.get[Map[String, String]]("attrs").map { case (attr, attrVal) =>
        (attr, attrVal)
      })
    }
  }
}

作为参考,这是我当前尝试参考的方式:

  val resellerEnvMap = conf.get[Map[String, CustomerConfig]]("customers").map {
    case (customer, customerConfig) =>
      customer -> customerConfig.attrs.map {
        case (attr, attrVal) =>
          attr -> new Obj(attrVal, customerConfig.clientId)
      }
  }

基于custom config loader documentation

问题在于,根据我认为的API docsconfig.get[A]不存在(config.getMap[K, V]也没有)。我想要一种从配置文件填充map的方法。我的最终目标是在Map[String, Map[String, (String, String)]]的功能范围内填充任何内容,其中第一个String是客户名称,第二个是属性名称,第三个是属性值,最后,第四个是客户ID。

1 个答案:

答案 0 :(得分:3)

播放2.6使用com.typesafe:config 1.3.2,而您发布的链接似乎来自版本2?这是一种实现方法:

object CustomerConfig {
  implicit val configLoader: ConfigLoader[CustomerConfig] = new ConfigLoader[CustomerConfig] {
    def load(rootConfig: Config, path: String): CustomerConfig = {
      val config = rootConfig.getConfig(path)
      import scala.collection.JavaConverters._

      val attrConfig = config.getConfig("attrs")
      CustomerConfig(
        clientId = config.getString("clientId"),
        attrs = attrConfig.entrySet().asScala.map { entry =>
          (entry.getKey, attrConfig.getString(entry.getKey))
        }.toMap
      )
    }
  }
}