拓冰建站拓冰建站
首页 / 资讯中心 / 正文

@Value与@ConfigurationProperties注解使用记录

目录背景介绍目标说明方案调试步骤说明方案1使用Value注解坑点问题1坑点问题2方案2使用ConfigurationProperties注解坑点问题1背景介绍最近工作中有个需求需要对一些特定的数据做定制化的开发和改造因此有需要对少量特定配置的信息写入配置文件涉及到对.yml文件中的配置信息进行获取。这里就不得不考虑具体是使用Value注解或者是使用ConfigurationProperties注解来实现对配置项的获取了。目标说明希望从application-{env}.yml文件中获取一个Map类型的key-value的数据结构。# 不要使用tpResultCustom tp-result-custom: map: aaa:bbb: ccc备注此处在yml文件中配置项均采用全小写字母-的方式进行配置否则后期在使用代码获取配置项的过程中可能会遇到报错的问题。另外key 包含冒号aaa:bbb一定要保留两侧的单引号。Configuration property name tpResultCustom is not valid: Invalid characters: R, C Bean: tpResultCustomProperties Reason: Canonical names should be kebab-case (- separated), lowercase alpha-numeric characters and must start with a letter方案调试步骤说明方案1使用Value注解由于使用Value注解相对比较简单且本次需求我这边仅需要拿到一个配置项Map所以我第一选择想使用的就是Value注解来进行处理可以不用添加一个配置管理的类。然而这个比较偷懒的想法让我是踩坑连连。坑点问题1$Value(${tp-result-custom.map}) private MapString, String tpResultCustomMap; Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder tpResultCustom.map in value ${tpResultCustom.map}问题原因Value不能直接注入MapSpring 不支持这种写法必然抛占位符无法解析异常。坑点问题2如果需要强行使用Value配置项的写法会很不有利于代码的扩展。只能单独取某一个 key不能一次性取整个map。// 单条key取值 Value(${tp-result-custom.map.aaa:bbb}) private String msg;方案2使用ConfigurationProperties注解添加如下配置类代码tp-result-custom: map: aaa:bbb: cccComponent ConfigurationProperties(prefix tp-result-custom) Data public class TpResultCustomProperties { private MapString, String map; }然而采用此种方案时候也并不是一帆风顺针对我本次的需求中遇到的问题则会有如下的问题点。坑点问题1代码在获取YAML 里键 aaa:bbb 被 SpringBoot 绑定时冒号丢失问题原因Spring Boot 配置绑定过程中会对 Map 的 key 执行属性名称规范化relaxed binding 宽松绑定自动把 : 当作分隔符处理、直接抹除。最终采用的处理方式1yml文件处修改记录方式:tp-result-custom: list: - key: aaa:bbb value: ccc2代码层面也修改获取方式:Data Component ConfigurationProperties(prefix tp-result-custom) public class TpResultCustomProperties { private ListItem list; Data public static class Item { private String key; private String value; } // 提供工具方法快速转Map public MapString, String toMap() { return list.stream() .collect(Collectors.toMap(Item::getKey, Item::getValue)); } }
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门