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

相关推荐
量化分析码农5 分钟前
股票历史数据的复权参数对照:多级别返回的字段与数值差异
java·javascript·后端
猫猫不是喵喵.15 分钟前
从0到1创建一个微服务项目
java·数据库·微服务·1024程序员节
瑞雪兆丰年兮26 分钟前
JavaWeb-day13-SpringBootWeb事务管理&AOP
java·开发语言·springboot·javaweb·事务·web·aop
曲径海盗35 分钟前
Try-Except怎么用,3个追问解答在自动化下的应用
java·jvm·oracle
Cosolar2 小时前
极简智库:快速搭建你的开源项目教程阅读平台,让 docs/ 目录被更多人看见
java·架构·github
nice_lcj5202 小时前
【从零理解 Spring AI · 16】Agent 与工作流:什么该写死,什么该让模型决定
java·人工智能·后端·spring ai·ai应用开发
北京云帆互联科技2 小时前
云帆培训考试系统更新说明:v9.3.0
java·学习
学长毕设3 小时前
基于SpringBoot的景点管理系统-附源码
java·spring boot·后端
sxlishaobin4 小时前
Maven Setting详解
java·学习·maven
知守观4 小时前
一个方法两个触发口:反编译 XXL-Job 后,我看清了 inner/job 子包的裸奔现状
java·spring boot·微服务