在 spring boot 中,读取配置文件(如 application.properties/application.yml)的方式丰富且灵活,核心可分为基础注解式、编程式、类型安全绑定三大类,以下是主流方式的详细总结:
一、核心前提:配置文件基础
spring boot 默认加载 src/main/resources 下的 application.properties 或 application.yml,也可通过 spring.config.name/spring.config.location 自定义配置文件路径。
方式1:@value 注解(基础单个属性读取)
核心特点
最基础、轻量的方式,直接绑定单个配置项到字段/方法参数,支持简单类型转换、默认值、spel 表达式。
使用示例
1. 配置文件(application.yml)
app:
name: demo-app
port: 8080
desc: ${app.name}-${app.port} # spel 拼接2. 代码绑定
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
@component
public class appconfig {
// 直接绑定单个属性
@value("${app.name}")
private string appname;
// 绑定并设置默认值(配置不存在时使用)
@value("${app.version:1.0.0}")
private string appversion;
// 绑定 spel 拼接的属性
@value("${app.desc}")
private string appdesc;
}优缺点
- ✅ 优点:简单易用,适合少量零散配置;
- ❌ 缺点:不支持复杂对象、无类型校验、配置多时代码冗余,无法自动刷新(需结合
@refreshscope)。
方式2:@configurationproperties(类型安全绑定,推荐)
核心特点
将一组相关配置绑定到 java 实体类,支持嵌套对象、类型校验、前缀分组,是 spring boot 推荐的配置绑定方式。
使用步骤
1. 配置文件(application.yml)
app:
name: demo-app
port: 8080
database:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
servers:
- 192.168.1.1
- 192.168.1.22. 绑定实体类
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.stereotype.component;
import java.util.list;
// 前缀指定配置分组,需配合 @component 或 @enableconfigurationproperties 生效
@component
@configurationproperties(prefix = "app")
public class appproperties {
private string name;
private integer port;
private database database; // 嵌套对象
private list<string> servers; // 集合
// 嵌套类
public static class database {
private string url;
private string username;
private string password;
// getter/setter
}
// 必须提供 getter/setter(spring 反射赋值)
public string getname() { return name; }
public void setname(string name) { this.name = name; }
// 其他字段的 getter/setter
}3. 启用配置(可选)
若实体类未加 @component,需在配置类中通过 @enableconfigurationproperties 启用:
import org.springframework.boot.context.properties.enableconfigurationproperties;
import org.springframework.context.annotation.configuration;
@configuration
@enableconfigurationproperties(appproperties.class)
public class config {
}增强特性
- 支持 jsr-380 校验(加
@validated+ 校验注解):@component @configurationproperties(prefix = "app") @validated public class appproperties { @notblank(message = "应用名称不能为空") private string name; // ... } - 支持配置自动刷新(结合
@refreshscope)。
优缺点
- ✅ 优点:类型安全、支持嵌套/集合、配置分组清晰、可校验;
- ❌ 缺点:需编写实体类,略繁琐(但可通过 lombok 简化)。
方式3:environment 接口(编程式读取)
核心特点
spring 核心环境接口,可动态读取所有配置(包括系统属性、环境变量、配置文件),支持配置占位符解析。
使用示例
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.core.env.environment;
import org.springframework.stereotype.component;
@component
public class envconfig {
@autowired
private environment env;
public void getconfig() {
// 读取单个配置
string appname = env.getproperty("app.name");
// 读取并指定默认值
integer appport = env.getproperty("app.port", integer.class, 8080);
// 读取嵌套配置
string dburl = env.getproperty("app.database.url");
}
}扩展能力
- 支持配置文件激活:
env.getactiveprofiles()(获取激活的环境,如 dev/prod); - 支持判断配置是否存在:
env.containsproperty("app.name")。
优缺点
- ✅ 优点:灵活,支持动态读取、多环境适配,无需绑定实体类;
- ❌ 缺点:无类型安全(需手动转换类型)、零散读取时代码冗余。
方式4:原生 properties/yml 读取(手动加载)
核心特点
脱离 spring 容器,手动加载配置文件(适合非 spring 管理的代码),支持 properties 和 yml 格式。
示例1:手动读取 properties 文件
import java.io.ioexception;
import java.io.inputstream;
import java.util.properties;
public class manualpropertiesreader {
public static void main(string[] args) throws ioexception {
properties props = new properties();
// 加载 classpath 下的配置文件
try (inputstream is = manualpropertiesreader.class.getclassloader().getresourceasstream("application.properties")) {
props.load(is);
string appname = props.getproperty("app.name");
}
}
}示例2:手动读取 yml 文件(需依赖 snakeyaml)
<!-- pom.xml 引入依赖 -->
<dependency>
<groupid>org.yaml</groupid>
<artifactid>snakeyaml</artifactid>
</dependency>import org.yaml.snakeyaml.yaml;
import java.io.inputstream;
import java.util.map;
public class manualymlreader {
public static void main(string[] args) {
yaml yaml = new yaml();
try (inputstream is = manualymlreader.class.getclassloader().getresourceasstream("application.yml")) {
map<string, object> data = yaml.load(is);
// 读取嵌套配置
map<string, object> app = (map<string, object>) data.get("app");
string appname = (string) app.get("name");
}
}
}优缺点
- ✅ 优点:完全脱离 spring,灵活控制加载逻辑;
- ❌ 缺点:需手动处理文件加载、类型转换、嵌套结构,无 spring 自动装配能力。
方式5:@propertysource 加载自定义配置文件
核心特点
加载非默认名称/路径的配置文件(如 custom.properties),配合 @value 或 @configurationproperties 使用。
使用示例
1. 自定义配置文件(custom.properties)
custom.name=my-custom-app custom.age=20
2. 加载并绑定
import org.springframework.context.annotation.propertysource;
import org.springframework.stereotype.component;
import org.springframework.beans.factory.annotation.value;
@component
// 加载自定义 properties 文件(仅支持 properties,不直接支持 yml)
@propertysource("classpath:custom.properties")
public class customconfig {
@value("${custom.name}")
private string customname;
}扩展:加载 yml 文件(需自定义工厂)
@propertysource 原生不支持 yml,需自定义 propertysourcefactory:
import org.springframework.core.env.mappropertysource;
import org.springframework.core.io.support.encodedresource;
import org.springframework.core.io.support.propertysourcefactory;
import org.yaml.snakeyaml.yaml;
import java.util.map;
public class ymlpropertysourcefactory implements propertysourcefactory {
@override
public org.springframework.core.env.propertysource<?> createpropertysource(string name, encodedresource resource) {
yaml yaml = new yaml();
map<string, object> data = yaml.load(resource.getinputstream());
return new mappropertysource(resource.getresource().getfilename(), data);
}
}使用:
@propertysource(value = "classpath:custom.yml", factory = ymlpropertysourcefactory.class)
@component
public class customymlconfig {
@value("${custom.name}")
private string customname;
}优缺点
- ✅ 优点:支持加载自定义配置文件,补充默认配置;
- ❌ 缺点:原生不支持 yml,需自定义工厂;多文件加载时需逐个声明。
各方式对比与选型建议
| 方式 | 类型安全 | 支持嵌套/集合 | 配置分组 | 手动加载 | 推荐场景 |
|---|---|---|---|---|---|
| @value | ❌ | ❌ | ❌ | ❌ | 少量零散配置、简单值绑定 |
| @configurationproperties | ✅ | ✅ | ✅ | ❌ | 大量相关配置、类型安全场景 |
| environment | ❌ | ✅(手动解析) | ❌ | ❌ | 动态读取、多环境适配、编程式 |
| 原生手动加载 | ❌ | ✅(手动解析) | ❌ | ✅ | 非 spring 管理代码、自定义加载 |
| @propertysource | 取决于绑定方式 | ✅ | ✅ | ❌ | 加载自定义配置文件 |
选型总结
- 日常开发优先用
@configurationproperties(类型安全、易维护); - 零散简单配置用
@value; - 动态读取/多环境适配用
environment; - 非 spring 代码或自定义加载逻辑用原生手动读取;
- 需加载自定义配置文件时结合
@propertysource。
到此这篇关于spring boot中读取配置文件的5种方式汇总(最新整理)的文章就介绍到这了,更多相关spring boot读取配置文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论