Spring Boot 的配置加载优先级和合并机制如下:
Spring Boot 配置加载优先级(从高到低)
1. 完整加载顺序
1. file:./config/application.yml ← 最高优先级
2. file:./application.yml
3. classpath:/config/application.yml
4. classpath:/application.yml ← JAR内部(最低优先级)
2. 具体说明
优先级 1:./config/application.yml(最高)
sample/target/
├── sample-1.10.0.jar
└── config/
└── application.yml # ← 这个优先级最高
优先级 2:./application.yml
sample/target/
├── sample-1.10.0.jar
└── application.yml # ← 这个优先级第二
优先级 3:classpath:/config/application.yml
如果 JAR 内部有 BOOT-INF/classes/config/application.yml
优先级 4:classpath:/application.yml(最低)
JAR 内部的 BOOT-INF/classes/application.yml
配置合并机制
Spring Boot 会合并所有找到的配置文件,而不是完全替换:
示例说明
假设有以下配置:
JAR 内部的 application.yml:
spring:
datasource:
url: jdbc:mysql://localhost:3306/cloud_sample
username: root
password: root
redis:
host: localhost
port: 6379
mqtt:
BASIC:
host: 192.168.1.100
port: 1883
username: JavaServer
password: 123456
外部的 ./config/application.yml:
spring:
datasource:
url: jdbc:mysql://prod-server:3306/cloud_sample # 覆盖
username: admin # 覆盖
# password 未配置,使用JAR内部的 root
mqtt:
BASIC:
host: 192.168.1.200 # 覆盖
# port 未配置,使用JAR内部的 1883
# username 未配置,使用JAR内部的 JavaServer
最终生效的配置:
spring:
datasource:
url: jdbc:mysql://prod-server:3306/cloud_sample # 来自外部
username: admin # 来自外部
password: root # 来自JAR内部
redis:
host: localhost # 来自JAR内部
port: 6379 # 来自JAR内部
mqtt:
BASIC:
host: 192.168.1.200 # 来自外部
port: 1883 # 来自JAR内部
username: JavaServer # 来自JAR内部
password: 123456 # 来自JAR内部
实际应用场景
场景 1:只覆盖部分配置
外部配置文件只需要包含需要修改的配置项:
# ./config/application.yml
spring:
datasource:
druid:
url: jdbc:mysql://prod-db:3306/cloud_sample
username: prod_user
password: prod_password
mqtt:
BASIC:
host: mqtt.prod.example.com
DRC:
host: ws-mqtt.prod.example.com
其他配置(如 Redis、JWT 等)会继续使用 JAR 内部的默认值。
场景 2:完全覆盖
如果需要完全覆盖某个配置块,需要完整定义:
# ./config/application.yml
mqtt:
BASIC:
protocol: MQTT
host: new-mqtt-server.com
port: 1883
username: new_user
password: new_password
client-id: new-client-id
path: ""
DRC:
protocol: WS
host: new-ws-server.com
port: 8083
path: /mqtt
username: new_user
password: new_password
验证配置加载顺序
启动应用时,可以通过日志查看加载的配置文件:
java -jar sample/target/sample-1.10.0.jar --debug
日志中会显示:
The following profiles are active:
Loaded config file 'file:./config/application.yml'
Loaded config file 'file:./application.yml'
Loaded config file 'classpath:/application.yml'
总结
- 外部配置文件优先级更高:
./config/application.yml>./application.yml> JAR 内部配置 - 配置会合并:外部配置覆盖相同键的值,未定义的键继续使用内部配置
- 推荐做法:外部配置文件只包含需要修改的配置项,其他使用默认值
这样可以在不重新打包的情况下,灵活调整生产环境的配置。
2513

被折叠的 条评论
为什么被折叠?



