Scala中用PureConfig+Enumeratum读取枚举键Map配置失败求助
解决PureConfig读取枚举键Map的问题
问题根源
你这问题有两个关键原因:
- PureConfig处理Map的枚举键时,需要KeyDecoder(不是普通的Decoder)把配置里的字符串键转成枚举类型,默认的自动导入不会生成这个实例。
MyConfig里的path是Ssystem枚举类型,但配置里写的是"samplepath1"这种普通字符串,根本没法对应到枚举值。
修复步骤
1. 给枚举加KeyDecoder实例
在Ssystem的伴生对象里,显式加个KeyDecoder,用pureconfig-enumeratum提供的方法生成就行,刚好匹配你用的连字符格式:
import pureconfig.KeyDecoder import pureconfig.module.enumeratum._ object Ssystem extends Enum[Ssystem] { val values = findValues // 加这个,让PureConfig能把配置里的字符串键转成枚举 implicit val keyDecoder: KeyDecoder[Ssystem] = KeyDecoder.fromEnum(this) case object MyEnumA extends Ssystem("testFieldEnum1") case object MyEnumB extends Ssystem("testFieldEnum2") }
2. 改配置里的path值
把配置里的path改成枚举对应的连字符格式,和Map的键保持一致,这样才能映射到Ssystem枚举:
target { my-enum-a= { path : "my-enum-a" // 原来的samplepath1不对,改成枚举对应的字符串 link : "samplehttp1" } my-enum-b = { path : "my-enum-b" // 同样修正 link : "samplehttp2" } }
3. 确认导入没丢
保持原有的导入,尤其是pureconfig.module.enumeratum._,这个包提供了枚举相关的解码工具。
修正后的完整代码
import enumeratum.EnumEntry.Hyphencase import enumeratum._ import pureconfig.{ConfigSource, KeyDecoder} import pureconfig.generic.auto._ import pureconfig.module.enumeratum._ object CheckPureConfig extends App { private val myConf = ConfigSource.default.loadOrThrow[SsystemConf] println(myConf) } case class SsystemConf(target: Map[Ssystem, MyConfig]) case class MyConfig(path: Ssystem, link: String) sealed abstract class Ssystem(myField: String) extends EnumEntry with Hyphencase { def printit() = myField } object Ssystem extends Enum[Ssystem] { val values = findValues // 新增的KeyDecoder implicit val keyDecoder: KeyDecoder[Ssystem] = KeyDecoder.fromEnum(this) case object MyEnumA extends Ssystem("testFieldEnum1") case object MyEnumB extends Ssystem("testFieldEnum2") }
这样改完,PureConfig就能正确解析枚举键的Map,MyConfig里的path字段也能正常映射了。
内容的提问来源于stack exchange,提问作者gabby
相关产品推荐
相关产品推荐

