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的结构匹配现有层级:
- 定义属性承载类:
@Getter @Setter public class BreedAttributes { private List<String> attributes; }
- 修改
DogConfig定义:
@Getter @Setter @Configuration @ConfigurationProperties(prefix = "doginfo") public class DogConfig extends HashMap<BreedEnum, BreedAttributes> { }
使用这种方式,原配置的doginfo.PITBULL.attributes[0]可以直接绑定到对应枚举Key对应的BreedAttributes对象的attributes列表中。
内容的提问来源于stack exchange,提问作者ekapitu
相关产品推荐
相关产品推荐

