You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring ConfigurationProperties如何绑定Enum为键List为值的Map属性

问题原因

你当前的配置文件层级和DogConfig的属性结构不匹配:DogConfig中attributes是doginfo前缀下的二级Map属性,但你写的application.properties把枚举值作为了doginfo下的一级字段,层级对应不上,因此绑定失败。

解决方案(推荐,改动最小)

调整application.properties的写法,匹配attributes Map的层级结构即可:

# 格式规则:前缀.Map属性名.[枚举Key].[列表下标] = 配置值
doginfo.attributes[PITBULL][0]=attrP0
doginfo.attributes[PITBULL][1]=attrP1
doginfo.attributes[CORGI][0]=attrC0

如果调整后还是绑定为null,补充以下检查:

  • 确认启动类添加了@ConfigurationPropertiesScan注解,扫描到DogConfig所在的包(Spring Boot 2.2+支持)
  • 低版本Spring Boot可以在DogConfig上额外添加@EnableConfigurationProperties(DogConfig.class)注解,显式注册配置类

可选方案:适配原有配置写法

如果你不想修改现有的application.properties内容,可以调整DogConfig的结构匹配现有层级:

  1. 定义属性承载类:
@Getter
@Setter
public class BreedAttributes {
    private List<String> attributes;
}
  1. 修改DogConfig定义:
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "doginfo")
public class DogConfig extends HashMap<BreedEnum, BreedAttributes> {
}

使用这种方式,原配置的doginfo.PITBULL.attributes[0]可以直接绑定到对应枚举Key对应的BreedAttributes对象的attributes列表中。


内容的提问来源于stack exchange,提问作者ekapitu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:09:01