当前位置: 代码网 > it编程>编程语言>Java > SpringBoot中ConfigurationProperties使用详解

SpringBoot中ConfigurationProperties使用详解

2026年01月26日 Java 我要评论
在spring boot中,@configurationproperties 是一个核心注解,用于将外部配置信息(如 application.properties、application.yml、环境

在spring boot中,@configurationproperties 是一个核心注解,用于将外部配置信息(如 application.propertiesapplication.yml、环境变量、命令行参数等)自动绑定到javabean的属性上,实现配置与代码的解耦。

核心作用

通过 @configurationproperties,可以避免在代码中硬编码配置(如数据库地址、端口号、第三方api密钥等),而是从外部配置源动态读取,方便环境切换(开发、测试、生产)。

基本使用步骤

1. 引入依赖(默认已包含)

@configurationproperties 属于spring boot核心功能,只要项目引入了 spring-boot-starter(或任意 starter,如 spring-boot-starter-web),就会自动包含相关依赖,无需额外添加。

2. 创建配置绑定实体类

定义一个javabean,使用 @configurationproperties 注解指定配置前缀(prefix),并通过属性名与配置文件中的key对应。

示例:绑定数据库相关配置

import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;

// 前缀为"spring.datasource",对应配置文件中"spring.datasource.xxx"的配置
@configurationproperties(prefix = "spring.datasource")
@component // 注册为spring组件,使其被扫描并绑定配置
public class datasourceproperties {
    // 对应配置文件中的"spring.datasource.url"
    private string url;
    // 对应"spring.datasource.username"
    private string username;
    // 对应"spring.datasource.password"
    private string password;
    // 对应"spring.datasource.driver-class-name"(支持宽松绑定,见下文)
    private string driverclassname;

    // 必须提供getter和setter(spring通过setter注入配置值)
    public string geturl() { return url; }
    public void seturl(string url) { this.url = url; }

    public string getusername() { return username; }
    public void setusername(string username) { this.username = username; }

    // 省略其他getter/setter
}

3. 外部配置文件(application.yml 或 application.properties)

在配置文件中定义对应前缀的配置项,属性名与实体类的属性名通过“宽松绑定”规则匹配。

application.yml 示例

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.driver # 对应实体类的driverclassname

application.properties 示例

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver

4. 启用配置绑定(两种方式)

  • 方式1:在实体类上添加 @component 注解(如步骤2示例),使其被spring扫描并注册为bean,自动触发配置绑定。
  • 方式2:在配置类上使用 @enableconfigurationproperties 显式指定需要绑定的类(适用于实体类未加 @component 的场景):
    import org.springframework.boot.context.properties.enableconfigurationproperties;
    import org.springframework.context.annotation.configuration;
    
    @configuration
    // 显式启用datasourceproperties的配置绑定
    @enableconfigurationproperties(datasourceproperties.class)
    public class myconfig {
    }
    

5. 在代码中使用绑定的配置

通过依赖注入(@autowired)将绑定好的实体类注入到service/controller中,直接使用配置值。

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
public class testcontroller {

    // 注入绑定了配置的实体类
    @autowired
    private datasourceproperties datasourceproperties;

    @getmapping("/db-info")
    public string getdbinfo() {
        return "数据库url:" + datasourceproperties.geturl() + 
               ",用户名:" + datasourceproperties.getusername();
    }
}

关键特性

1. 宽松绑定(relaxed binding)

配置文件中的key与实体类属性名无需严格一致,支持多种命名风格转换:

  • 配置文件中:driver-class-name(短横线分隔,kebab-case)
  • 实体类中:driverclassname(驼峰式,camelcase)
  • 其他支持:下划线(driver_class_name)、全大写(driver_class_name)等。

2. 类型转换

spring会自动将配置文件中的字符串值转换为实体类属性的类型(如 intbooleanlistmap 等)。

示例:绑定集合类型

@configurationproperties(prefix = "app")
@component
public class appproperties {
    private list<string> allowedorigins; // 对应app.allowed-origins
    private map<string, string> configmap; // 对应app.config-map

    // getter/setter
}

配置文件(application.yml)

app:
  allowed-origins:
    - http://localhost:8080
    - http://example.com
  config-map:
    key1: value1
    key2: value2

3. 配置校验

结合 @validated 和jsr-303校验注解(如 @notnull@min@pattern),可对配置值进行合法性校验,避免无效配置。

示例

import org.springframework.validation.annotation.validated;
import javax.validation.constraints.notempty;
import javax.validation.constraints.notnull;

@configurationproperties(prefix = "app")
@component
@validated // 启用校验
public class appproperties {

    @notempty(message = "应用名称不能为空") // 校验非空
    private string name;

    @notnull(message = "端口号不能为空") // 校验非null
    private integer port;

    // getter/setter
}

若配置文件中未设置 app.nameapp.port,启动时会抛出校验异常,快速发现配置问题。

4. 配置元数据(提高开发体验)

通过添加 spring-boot-configuration-processor 依赖,可生成配置元数据,在ide中编写配置文件时获得自动提示(如属性名、类型、描述)。

添加依赖(pom.xml)

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-configuration-processor</artifactid>
    <optional>true</optional>
</dependency>

添加后,ide(如idea)会在编写 application.yml 时提示 spring.datasource.url 等属性,减少拼写错误。

与 @value 的区别

特性@configurationproperties@value
用途批量绑定多个配置属性到实体类单个属性注入(如 @value("${app.name}"))
类型转换自动支持复杂类型(list、map等)需手动处理复杂类型转换
校验支持支持(结合 @validated)不支持
宽松绑定支持不支持(需严格匹配key)
元数据提示支持(需processor依赖)不支持

建议:配置项较多时优先使用 @configurationproperties;单个简单配置可使用 @value

总结

@configurationproperties 是spring boot中管理外部配置的核心工具,通过“配置文件→实体类→代码使用”的流程,实现了配置的集中管理和动态绑定,尤其适合多环境配置、复杂配置场景,大幅提升了配置的可维护性。

到此这篇关于springboot中configurationproperties使用详解的文章就介绍到这了,更多相关configurationproperties使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com