0%

springboot配置文件

Spring Boot 配置文件详解:类型、加载顺序、自定义配置与实战指南

Spring Boot 的核心优势之一是 “约定大于配置”,但实际开发中仍需通过配置文件自定义参数(如端口、数据库连接、第三方服务密钥等)。Spring Boot 支持多种配置文件格式和加载策略,从 “配置文件类型→加载顺序→外部配置引入→自定义配置→bootstrap 与 application 区别→配置优先级” 六个维度,系统讲解 Spring Boot 配置文件的使用方法与底层逻辑,帮你彻底掌握配置管理技巧。

Spring Boot 配置文件的两种核心类型

Spring Boot 支持两种主流配置文件格式:application.properties(键值对格式)和 application.yml(YAML 格式),二者功能完全一致,仅语法风格不同,可根据团队习惯选择。

1. 格式对比与语法规则

(1)application.properties(传统键值对格式)
  • 语法:采用 key=value 结构,层级关系通过 . 分隔;
  • 优点:语法简单,兼容性好(所有 Spring 版本支持);
  • 缺点:层级嵌套时冗余(需重复写前缀)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
# 服务器配置
server.port=8080
server.servlet.context-path=/demo

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

# 自定义配置
custom.name=Spring Boot
custom.version=2.7.10
(2)application.yml(YAML 缩进格式,推荐)
  • 语法:采用 “缩进 + 冒号” 表示层级关系,键值对用 key: value(冒号后需加空格);
  • 优点:层级清晰,冗余少,支持列表、对象等复杂结构;
  • 缺点:对缩进敏感(必须用空格,不能用 Tab),低版本 Spring 需额外依赖(Spring Boot 1.2+ 已内置支持)。

示例(与上述 properties 配置等价):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 服务器配置(层级通过缩进体现)
server:
port: 8080
servlet:
context-path: /demo

# 数据库配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456

# 自定义配置(支持对象结构)
custom:
name: Spring Boot
version: 2.7.10
features: [自动配置, 嵌入式容器, Starter依赖] # 列表格式

2. 两种格式的优先级

若同一目录下同时存在 application.propertiesapplication.yml

  • 优先级application.properties > application.yml(相同配置项,properties 会覆盖 yml);
  • 建议:项目中统一使用一种格式(推荐 yml,层级更清晰),避免混合使用导致配置冲突。

Spring Boot 配置文件的默认加载顺序

Spring Boot 启动时会自动扫描4 个默认位置application.properties/yml 文件,按 “优先级从高到低” 加载,高优先级配置会覆盖低优先级配置(若配置项重复),且所有位置的配置文件会合并生效(非重复项叠加)。

1. 默认加载位置(优先级从高到低)

加载路径 位置描述 适用场景
file:./config/ 项目根目录下的 config 文件夹 生产环境自定义配置(不纳入代码仓库,避免泄露敏感信息)
file:./ 项目根目录下 本地开发临时配置(如测试端口)
classpath:/config/ 项目 resources 目录下的 config 文件夹 代码仓库中的通用配置(如数据库连接模板)
classpath:/ 项目 resources 目录下(默认位置) 代码仓库中的核心配置(如应用名称、默认端口)

示例

  • file:./config/application.yml 配置 server.port=8081classpath:/application.yml 配置 server.port=8080,最终端口为 8081(高优先级覆盖低优先级);
  • file:./config/application.yml 配置 server.port=8081classpath:/application.yml 配置 spring.datasource.url=xxx,最终两个配置都会生效(非重复项叠加)。

2. 自定义配置文件位置与名称

若默认位置无法满足需求(如配置文件放在服务器特定路径),可通过以下方式自定义:

(1)命令行参数指定位置

启动 JAR 包时,通过 --spring.config.location 指定配置文件路径(多个路径用逗号分隔):

1
2
3
4
5
# 示例1:指定单个外部配置文件
java -jar demo.jar --spring.config.location=/opt/config/application.yml

# 示例2:指定多个配置文件(外部文件 + 内部文件)
java -jar demo.jar --spring.config.location=/opt/config/application.yml,classpath:/application.yml
(2)命令行参数指定文件名

默认配置文件名为 application,若需修改(如 custom.yml),通过 --spring.config.name 指定:

1
2
# 加载 custom.yml(需确保文件在默认位置或通过 spring.config.location 指定路径)
java -jar demo.jar --spring.config.name=custom
(3)VM 参数指定(启动时传入)

通过 -D 传入 VM 参数,效果与命令行参数一致:

1
2
# 指定配置文件位置
java -Dspring.config.location=/opt/config/application.yml -jar demo.jar

引入外部配置文件:@PropertySource 注解

默认配置文件(application.*)通常用于全局配置,若需引入额外配置文件(如 test.propertiescustom.properties),可通过 @PropertySource@PropertySources 注解实现。

1. 单个外部配置文件:@PropertySource

在配置类上添加 @PropertySource,指定外部配置文件路径(支持 classpath 或绝对路径):

1
2
3
4
5
6
7
8
9
10
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

// 标记为配置类
@Configuration
// 引入 classpath 下的 test.properties 文件
@PropertySource(value = "classpath:test.properties")
public class TestConfig {
// 配置文件中的属性会自动加载到 Spring 环境中
}

test.properties 内容

1
2
test.msg=Hello from external file
test.version=1.0.0

2. 多个外部配置文件:@PropertySources

若需引入多个文件,用 @PropertySources 包裹多个 @PropertySource

1
2
3
4
5
6
7
8
9
10
11
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;

@Configuration
@PropertySources({
@PropertySource(value = "classpath:test1.properties"),
@PropertySource(value = "classpath:test2.properties")
})
public class MultiConfig {
}

3. 注意事项

  • 路径格式classpath: 表示从项目 resources 目录读取,绝对路径需写全路径(如 file:/opt/config/test.properties);

  • 编码问题:若配置文件含中文,需指定编码(Spring Boot 2.2+ 支持encoding属性):

    1
    @PropertySource(value = "classpath:test.properties", encoding = "UTF-8")
  • 优先级@PropertySource 引入的文件优先级低于默认配置文件(application.*),相同配置项会被默认文件覆盖。

自定义配置:@ConfigurationProperties 绑定

Spring Boot 提供 @ConfigurationProperties 注解,可将配置文件中的属性 “自动绑定” 到 Java 类的字段上,替代传统的 @Value 注解(更适合复杂对象配置)。

1. 核心步骤:配置绑定与注册

(1)定义配置类并绑定属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

// 1. 注册为 Spring 组件(必须,否则无法被扫描)
@Component
// 2. 绑定配置文件中前缀为 "custom" 的属性
@ConfigurationProperties(prefix = "custom")
public class CustomConfig {
// 字段名需与配置文件中 "custom" 前缀后的键一致(如 custom.name → name)
private String name;
private String version;
private String[] features; // 支持数组/列表类型

// 必须提供 getter 和 setter(Spring 通过反射注入值)
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getVersion() {
return version;
}

public void setVersion(String version) {
this.version = version;
}

public String[] getFeatures() {
return features;
}

public void setFeatures(String[] features) {
this.features = features;
}
}
(2)配置文件中添加对应属性(application.yml)
1
2
3
4
custom:
name: Spring Boot Demo
version: 2.7.10
features: [自动配置, 嵌入式Tomcat, Starter依赖]
(3)使用自定义配置

在 Controller 或 Service 中注入 CustomConfig 即可使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class CustomController {
// 注入自定义配置类
@Resource
private CustomConfig customConfig;

@GetMapping("/custom")
public CustomConfig getCustomConfig() {
return customConfig; // 返回配置信息,如 {"name":"Spring Boot Demo", "version":"2.7.10", ...}
}
}

2. 配置提示:添加依赖解决无提示问题

“自定义配置时无提示”,原因是缺少配置处理器依赖。添加以下依赖后,IDE(如 IDEA)会自动识别 @ConfigurationProperties 绑定的属性,提供补全和提示:

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional> <!-- 仅编译时需要,不打包到 JAR 中 -->
</dependency>

生效方式:添加依赖后,重新编译项目(mvn clean compile),IDE 会生成配置元数据(META-INF/spring-configuration-metadata.json),从而支持提示。

3. 非默认配置文件的绑定

若自定义配置不在默认 application.* 中,需结合 @PropertySource 指定文件路径:

1
2
3
4
5
6
7
8
9
10
11
import org.springframework.context.annotation.PropertySource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "custom")
// 指定配置文件路径(非默认文件)
@PropertySource(value = "classpath:custom.properties", encoding = "UTF-8")
public class CustomConfig {
// 字段与 getter/setter 同上
}

bootstrap 与 application 配置文件的核心区别

Spring Boot 存在两种上下文(Context),对应两种配置文件:bootstrap.*(父上下文)和 application.*(子上下文),二者加载时机和作用场景完全不同。

1. 核心差异对比

对比维度 bootstrap.* 配置文件 application.* 配置文件
加载时机 优先加载(父上下文初始化时),早于 application 后加载(子上下文初始化时),晚于 bootstrap
上下文归属 父上下文(Spring ApplicationContext) 子上下文(Spring Boot ApplicationContext)
配置覆盖规则 默认不可被覆盖(本地配置无法覆盖 bootstrap 配置) 可被覆盖(高优先级配置覆盖低优先级,如命令行参数)
核心作用 加载 “不可变配置”(如配置中心地址、加密密钥) 加载 “可变配置”(如服务器端口、数据库连接)
依赖场景 需引入 spring-cloud-starter(Spring Cloud 项目) 无需额外依赖(所有 Spring Boot 项目默认支持)

2. bootstrap 配置文件的典型应用场景

bootstrap.* 并非所有项目都需使用,仅在以下场景中必需:

(1)Spring Cloud 配置中心(Config Server)

当项目使用 Spring Cloud Config 从远程配置中心拉取配置时,需在 bootstrap.* 中配置配置中心地址(不可变),否则无法加载远程配置:

1
2
3
4
5
6
7
8
# bootstrap.yml(Spring Cloud 配置中心示例)
spring:
application:
name: demo-service # 服务名(用于拉取对应配置)
cloud:
config:
uri: http://config-server:8888 # 配置中心地址(不可变)
profile: dev # 环境(dev/test/prod)
(2)配置加密 / 解密

若配置文件中存在加密后的敏感信息(如数据库密码 {cipher}xxx),需在 bootstrap.* 中配置解密密钥(不可变),Spring Boot 会在加载配置时自动解密:

1
2
3
# bootstrap.yml(配置解密示例)
encrypt:
key: my-secret-key # 解密密钥(需保密,通常通过环境变量传入)
(3)固定不可变的基础配置

如服务注册中心地址(Eureka/Nacos)、日志配置等,需确保这些配置不被本地配置覆盖:

1
2
3
4
5
6
# bootstrap.yml(固定 Nacos 地址)
spring:
cloud:
nacos:
discovery:
server-addr: nacos-server:8848 # 不可变的注册中心地址

Spring Boot 配置加载的完整优先级

Spring Boot 加载配置的来源不仅包括配置文件,还包括命令行参数、系统属性等,优先级从高到低如下(高优先级配置会覆盖低优先级):

  1. 命令行参数(最高优先级):如 --server.port=8081,直接在启动命令中指定;
  2. JNDI 属性java:comp/env):Java 命名和目录接口中的属性;
  3. Java 系统属性System.getProperties()):如通过 -Dserver.port=8082 传入的 VM 参数;
  4. 操作系统环境变量:如 Linux 中的 SERVER_PORT=8083
  5. RandomValuePropertySource:生成随机值的配置(如 random.intrandom.uuid);
  6. JAR 包外部的 application-{profile}.\*:如 file:./config/application-dev.yml
  7. JAR 包内部的 application-{profile}.\*:如 classpath:/config/application-dev.yml
  8. JAR 包外部的 application.\*:如 file:./application.yml
  9. JAR 包内部的 application.\*:如 classpath:/application.yml
  10. @Configuration 类上的 @PropertySource:通过注解引入的外部配置文件;
  11. Spring 默认属性(最低优先级):Spring Boot 内置的默认配置(如 server.port=8080)。

示例

  • 若命令行参数指定 --server.port=8081,同时 application.yml 配置 server.port=8080,最终端口为 8081(命令行优先级更高);
  • 若操作系统环境变量 SERVER_PORT=8083,同时 Java 系统属性 -Dserver.port=8082,最终端口为 8082(系统属性优先级高于环境变量)。

配置文件实战最佳实践

  1. 格式选择:优先使用 application.yml,层级清晰且支持复杂结构;
  2. 配置分离:
    • 通用配置(如应用名称)放在 application.yml
    • 环境特定配置(如开发 / 生产端口)放在 application-dev.yml/application-prod.yml,通过 spring.profiles.active 激活;
  3. 敏感信息处理:
    • 避免在配置文件中硬编码敏感信息(如密码、密钥),优先通过环境变量或配置中心注入;
    • 必须硬编码时,使用 Spring Boot 加密功能(bootstrap.* 配置解密密钥);
  4. 自定义配置规范:
    • 所有自定义配置统一前缀(如 custom.),避免与 Spring 内置配置冲突;
    • 使用 @ConfigurationProperties 替代 @Value,支持批量绑定和类型校验;
  5. Spring Cloud 场景:
    • 配置中心地址、服务注册地址等不可变配置放在 bootstrap.yml
    • 业务配置(如数据库连接)放在 application.yml 或远程配置中心。

总结

Spring Boot 配置文件系统灵活且强大,核心要点可概括为:

  • 类型properties(简单)和 yml(推荐),按需选择;
  • 加载顺序:4 个默认位置从高到低,支持自定义路径;
  • 外部引入@PropertySource 加载额外配置文件;
  • 自定义绑定@ConfigurationProperties 实现配置与 Java 类绑定,需添加处理器依赖获取提示;
  • bootstrap 与 application:前者优先加载不可变配置(Spring Cloud 场景),后者加载可变配置;
  • 优先级:命令行参数最高,默认属性最低,覆盖规则需清晰

欢迎关注我的其它发布渠道

表情 | 预览
快来做第一个评论的人吧~
Powered By Valine
v1.3.10