Spring Boot 配置属性中的连字符解析

配置属性命名规则

在Spring Boot中,配置文件(如application.properties或application.yml)中的属性通常使用连字符(-)来分隔单词。这是为了遵循常见的配置命名约定,使得配置文件更易于阅读。

属性解析和松散绑定

Spring Boot支持所谓的松散绑定(Loose Binding),这意味着配置属性名称可以使用不同的格式,但最终都会映射到相同的Bean属性。例如,以下各种属性名格式都可以映射到同一个Bean属性:

  • outer.inner.anotherProperty
  • outer.inner.another-property
  • outer.inner.another_property
  • OUTER_INNER_ANOTHERPROPERTY

Spring Boot会自动处理这些不同格式的属性名,并将它们正确解析到对应的Bean属性上。

连字符的默认解析

当配置属性中包含连字符时,Spring Boot会自动解析这些连字符,并将其转换为相应的驼峰命名规则。这意味着,如果你有一个配置属性名为outer.inner.another-property,Spring Boot会将其解析为outer.inner.anotherProperty,并尝试将其值绑定到一个名为anotherProperty的Bean属性上。

示例

假设你有一个配置类如下:

java 复制代码
@ConfigurationProperties(prefix = "outer.inner")
public class MyProperties {

    private String anotherProperty;

    // Getter and setter methods
    public String getAnotherProperty() {
        return anotherProperty;
    }

    public void setAnotherProperty(String anotherProperty) {
        this.anotherProperty = anotherProperty;
    }
}

在application.properties中,你可以这样配置:

XML 复制代码
outer.inner.another-property=SomeValue

Spring Boot将会自动将another-property的值绑定到MyProperties类的anotherProperty属性上。这个过程是自动的,无需进行额外的配置或注解。

相关推荐
谢亮_vipxieliang41 分钟前
泛型擦除、通配符与 PECS 一次讲透
java·面试
八解毒剂1 小时前
【计组】中央处理器CPU
java·开发语言·计算机组成原理
打工仔折腾 AI2 小时前
工业场景下时序库与实时计算一体化架构选型实践对比
java·开发语言·后端·python·性能优化·架构·ai agent 实战
ZealSinger2 小时前
Java虚拟线程上线后瓶颈转移到哪看三层
java·开发语言·firefox
2601_961133282 小时前
盘立方软件指标文华期货公式下载
java
蜗牛互联网2 小时前
长任务多Agent共享文件系统的Manifest交接模式
java·人工智能·后端
Sirens.2 小时前
Java并发锁详解:六类锁策略与 synchronized 底层原理
java·前端·算法
sunshine22 girl3 小时前
Java学习五 面向对象高级5 内部类1
java·学习
苏supper4 小时前
Spring Boot多环境配置与打包运行
spring boot·后端·spring
天衍四九-4 小时前
【无标题】
前端·spring boot·mysql·nginx·docker