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

配置属性命名规则

在Spring Boot中,配置文件(如application.propertiesapplication.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属性上。这个过程是自动的,无需进行额外的配置或注解。

相关推荐
FreemanGordon31 分钟前
Java volatile 关键字
java
北京_宏哥32 分钟前
《手把手教你》系列基础篇(九十三)-java+ selenium自动化测试-框架设计基础-POM设计模式实现-上篇(详解教程)
java·前端·selenium
北京_宏哥39 分钟前
《手把手教你》系列基础篇(九十二)-java+ selenium自动化测试-框架设计基础-POM设计模式简介(详解教程)
java·selenium·前端工程化
当归10241 小时前
微服务与消息队列RabbitMQ
java·微服务
Lx3521 小时前
《从头开始学java,一天一个知识点》之:循环结构:for与while循环的使用场景
java·后端
Cache技术分享1 小时前
15. Java 如何声明一个变量来引用数组
java·前端
雷渊1 小时前
深入分析理解mysql的MVCC
java·数据库·面试
知其然亦知其所以然1 小时前
Java 高级面试题:Lock 到底比 synchronized 强在哪?
java·后端·面试
风象南1 小时前
Spring Boot 的 20个实用技巧
java·spring boot
Java陈序员1 小时前
IDEA 必备插件!轻松搞定 JSON 格式化!
java·json·intellij idea