【问题标题】:Play (Scala) Configuration Map Object播放(Scala)配置映射对象
【发布时间】:2018-07-12 17:47:19
【问题描述】:

我想访问以下配置

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

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

【问题讨论】:

    标签: scala playframework configuration typesafe-config


    【解决方案1】:

    Play 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
          )
        }
      }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多