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属性上。这个过程是自动的,无需进行额外的配置或注解。

相关推荐
红辣椒...5 分钟前
codex+第三方模型
java·服务器·前端
一个做软件开发的牛马15 分钟前
Java 继承与多态:从"是什么"到"能做什么"的设计思维
java·后端
不懂的浪漫25 分钟前
05|Netty ByteBuf 源码分析:为什么不用 Java ByteBuffer
java·netty
wapicn9931 分钟前
API接口调试笔记:从注册到第一个数据返回,全流程详解
java·开发语言·python·lua
程序员阿明34 分钟前
flowable集成flowable及其运行示例spring boot后端
java·spring boot·后端
代码不停41 分钟前
Spring IoC&DI
java·后端·spring
KANGBboy1 小时前
java知识二(数组)
java·开发语言·python
爱笑的源码基地1 小时前
智慧班牌源码:从后端SpringBoot到前端Vue2的全栈实现
java·大数据·云计算·源码·程序代码·智慧校园源码·智慧班牌源码
XiYang-DING1 小时前
【Spring】日志
java·数据库·spring
雪度娃娃1 小时前
转向现代C++——优先选用删除函数而非private未定义函数
java·jvm·c++