1 使用spring boot的@configurationproperties
@configurationproperties 是 spring boot 提供的一个强大注解,用于将外部配置文件(如 yaml 或 properties 文件)中的属性值绑定到 java 对象上。它是 spring boot 外部化配置的核心功能之一。
示例配置(application.yml)
app:
name: myapplication
version: 1.0.0
servers:
- dev.example.com
- prod.example.com创建配置类
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
import java.util.list;
@data
@component
@configurationproperties(prefix = "app")
public class appconfig {
private string name;
private string version;
private list<string> servers;
}使用配置类
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class mycontroller {
@autowired
private appconfig appconfig;
@getmapping("/info")
public string getappinfo() {
return "app: " + appconfig.getname() +
", version: " + appconfig.getversion() +
", servers: " + appconfig.getservers();
}
}2. 使用@value注解读取单个配置
@value 是 spring 框架提供的一个核心注解,用于从属性源(如 properties/yaml 文件、环境变量、系统属性等)中注入值到 spring 管理的 bean 中。
基本用法
- 注入简单值
@component
public class mycomponent {
@value("${app.name}")
private string appname;
@value("${app.version:1.0.0}") // 带默认值
private string appversion;
}对应的 application.yml:
app: name: myapplication # version 未设置时将使用默认值 1.0.0
- 注入系统属性
@value("${user.home}")
private string userhome; // 注入系统属性 user.home- 注入环境变量
@value("${java_home}")
private string javahome; // 注入环境变量 java_homeimport org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
@component
public class mycomponent {
@value("${app.name}")
private string appname;
@value("${app.version}")
private string appversion;
@value("${app.description:默认描述}") // 带默认值
private string appdescription;
// getters and setters
}3 @configurationproperties 详细介绍
@configurationproperties 是 spring boot 提供的一个强大注解,用于将外部配置文件(如 yaml 或 properties 文件)中的属性值绑定到 java 对象上。它是 spring boot 外部化配置的核心功能之一。
基本用法
1. 启用配置属性
首先需要在主类或配置类上添加 @enableconfigurationproperties 注解:
@springbootapplication
@enableconfigurationproperties
public class myapplication {
public static void main(string[] args) {
springapplication.run(myapplication.class, args);
}
}2. 创建配置属性类
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
@component
@configurationproperties(prefix = "myapp")
public class myappproperties {
private string name;
private string version;
private list<string> servers = new arraylist<>();
private database database;
// getters and setters
public static class database {
private string url;
private string username;
private string password;
// getters and setters
}
}3. 对应的 yaml 配置
myapp:
name: my application
version: 1.0.0
servers:
- server1.example.com
- server2.example.com
database:
url: jdbc:mysql://localhost:3306/mydb
username: admin
password: secret核心特性
1. 前缀绑定
prefix 属性指定了配置属性的前缀:
@configurationproperties(prefix = "myapp")
2. 宽松绑定 (relaxed binding)
spring boot 支持多种属性命名风格自动匹配:
myapp.database.url(properties 风格)myapp.database-url(kebab-case 风格)myapp.databaseurl(camelcase 风格)myapp_database_url(环境变量风格)
3. 类型安全
配置属性会自动转换为目标类型:
myapp: timeout: 5000 # 自动转换为 int enabled: true # 自动转换为 boolean ratio: 0.8 # 自动转换为 float
4. 嵌套属性
支持多层嵌套的配置结构:
public class myappproperties {
private database database;
public static class database {
private string url;
private int maxconnections;
}
}5. 集合类型支持
支持 list、set、map 等集合类型:
myapp:
servers:
- server1
- server2
endpoints:
api: /api/v1
auth: /auth对应的 java 类:
private list<string> servers; private map<string, string> endpoints;
高级特性
1. 属性验证
可以结合 jsr-303 验证注解:
import javax.validation.constraints.notempty;
import javax.validation.constraints.min;
@configurationproperties(prefix = "myapp")
@validated
public class myappproperties {
@notempty
private string name;
@min(1)
private int version;
// ...
}2. 默认值
可以在字段声明时提供默认值:
private int timeout = 3000; // 默认值 3000
3. 构造函数绑定 (spring boot 2.2+)
支持不可变对象的构造函数绑定:
@configurationproperties(prefix = "myapp")
public class myappproperties {
private final string name;
private final int version;
public myappproperties(string name, int version) {
this.name = name;
this.version = version;
}
// 只需要 getters
}4. 第三方组件配置
可以为第三方库创建配置属性类:
@configurationproperties(prefix = "thirdparty.service")
public class thirdpartyserviceproperties {
private string endpoint;
private string apikey;
// getters and setters
}最佳实践
- 集中管理配置:将相关配置属性组织在一个类中
- 使用嵌套类:对于复杂配置,使用静态内部类
- 添加验证:确保配置值的有效性
- 提供文档:使用
@configurationproperties的description属性或元数据文件 - 考虑不可变性:对于生产环境配置,考虑使用构造函数绑定
配置元数据
为了在 ide 中获得更好的支持,可以创建 additional-spring-configuration-metadata.json 文件:
{
"properties": [
{
"name": "myapp.name",
"type": "java.lang.string",
"description": "the name of the application."
},
{
"name": "myapp.database.url",
"type": "java.lang.string",
"description": "jdbc url for the database connection."
}
]
}与 @value 对比
| 特性 | @configurationproperties | @value |
|---|---|---|
| 松散绑定 | 支持 | 不支持 |
| 元数据支持 | 支持 | 不支持 |
| spel 表达式 | 不支持 | 支持 |
| 复杂类型 | 支持 | 有限支持 |
| 验证 | 支持 | 不支持 |
| 多个属性关联 | 方便 | 不方便 |
常见问题解决
属性未绑定:
- 确保类有
@component或通过@enableconfigurationproperties注册 - 检查前缀是否正确
- 确保属性有 setter 方法(除非使用构造函数绑定)
- 确保类有
类型不匹配:
- 检查 yaml 中的值是否能转换为目标类型
- 考虑使用
@durationunit或@datasizeunit指定单位
ide 警告:
- 添加
spring-boot-configuration-processor依赖 - 生成配置元数据
- 添加
@configurationproperties 是 spring boot 中处理外部配置的强大工具,特别适合管理大量相关配置属性,提供了类型安全、验证和良好组织结构的优势。
到此这篇关于java中读取yaml文件配置信息的文章就介绍到这了,更多相关java读取yaml配置信息内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论