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

Spring Boot:属性键规范格式互转及配置文件解析需求

可行方案建议

1. 优先使用Spring原生工具类(推荐)

Spring Boot提供了ConfigurationPropertyName类,专门用于将各种格式的属性名转换为规范的kebab-case格式,完全贴合Spring的规则,无需自己实现正则逻辑。

示例代码:

import org.springframework.boot.context.properties.source.ConfigurationPropertyName;

public String convertToCanonicalForm(String key) {
    return ConfigurationPropertyName.from(key).toString();
}

该方法能覆盖所有边缘场景:

  • 驼峰命名:databasePlatform → database-platform
  • 下划线命名:database_platform → database-platform
  • 大写混合:spring.JPA → spring.jpa
  • 数字混合:abc123Def → abc123-def、A123 → a123

2. 自定义正则实现(无Spring Boot依赖时)

如果无法引入Spring Boot依赖,可以自己实现正则逻辑覆盖所有转换场景,步骤如下:

  1. 将下划线替换为短横线
  2. 在小写字母/数字与大写字母之间插入短横线
  3. 统一转换为小写

代码实现:

public String convertToCanonicalForm(String key) {
    // 替换下划线为短横线
    String processed = key.replace('_', '-');
    // 处理小写/数字后接大写字母的驼峰场景
    processed = processed.replaceAll("([a-z0-9])([A-Z])", "$1-$2");
    // 转换为全小写
    return processed.toLowerCase();
}

验证示例:

输入值转换结果是否符合Spring规则
databasePlatformdatabase-platform是
dataBasePlatformdata-base-platform是
database_platformdatabase-platform是
spring.JPA.database_platformspring.jpa.database-platform是
abc123abc123是
a123a123是
A123a123是
ABC123Defabc123-def是

3. 不推荐使用你提供的两个函数的原因

  • 第一个函数:会错误地在数字前添加短横线(如abc123→abc-123),且开头大写字母加数字的场景会生成多余短横线(如A123→a-123),不符合Spring规则。
  • 第二个函数:不处理下划线和数字后接大写字母的场景,无法覆盖所有格式的属性键转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:06:39