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

相关推荐
呼啦啦啦啦啦啦啦啦2 小时前
常见的排序算法
java·算法·排序算法
anlogic3 小时前
Java基础 8.18
java·开发语言
练习时长一年3 小时前
AopAutoConfiguration源码阅读
java·spring boot·intellij-idea
源码宝5 小时前
【智慧工地源码】智慧工地云平台系统,涵盖安全、质量、环境、人员和设备五大管理模块,实现实时监控、智能预警和数据分析。
java·大数据·spring cloud·数据分析·源码·智慧工地·云平台
David爱编程5 小时前
面试必问!线程生命周期与状态转换详解
java·后端
LKAI.6 小时前
传统方式部署(RuoYi-Cloud)微服务
java·linux·前端·后端·微服务·node.js·ruoyi
HeyZoeHey6 小时前
Mybatis执行sql流程(一)
java·sql·mybatis
2301_793086876 小时前
SpringCloud 07 微服务网关
java·spring cloud·微服务
柳贯一(逆流河版)7 小时前
Spring 三级缓存:破解循环依赖的底层密码
java·spring·缓存·bean的循环依赖
Q_Q19632884759 小时前
python的电影院座位管理可视化数据分析系统
开发语言·spring boot·python·django·flask·node.js·php