1、配置文件
1.1、作用
Spring Boot 使用一个全局的配置文件,配置文件名称是固定的: application*.properties|yml|yaml
。
Spring Boot 是基于约定的,所以很多配置都有默认值,配置文件的作用就是修改 Spring Boot 自动配置的默认值。
若想使用自定义的配置替换默认配置,可以编写 application*.properties|yml|yaml
配置文件进行配置。
注:yaml 文件以 yml 或 yaml 为后缀都可,推荐使用 yml 后缀。
1.2、类型
传统格式 | 默认格式 :application*.properties,语法结构 :key=value
主流格式 | 官方推荐 :application*.yml,语法结构 :key:空格value
1.3、加载
三种类型配置文件都存在,其加载优先级为: properties > yml > yaml 。
不同配置文件中相同配置按照加载优先级相互覆盖(优先级高的覆盖低的),不同配置文件中不同配置全部保留。
1.4、分类
不同位置中的配置文件其加载优先级从高到低为:
- file :
./config/*.yml
,项目根目录下 config 目录下 - file :
./*.yml
,项目根目录下 - classpath:
config/application.yml
,类路径下 config 目录下 - classpath:
application.yml
,类路径下
多层级配置文件间的相同配置按照加载优先级相互覆盖(优先级高的覆盖低的),不同配置文件中不同配置全部保留。
2、配置多环境
2.1、YAML 单文件版
application.yml
spring:
profiles:
active: prod #启动指定环境
#公共配置...
---
spring:
config:
activate:
on-profile: dev #设置开发环境
server:
port: 8080
#其它配置...
---
spring:
profiles:
activate:
on-profile: test #设置测试环境
server:
port: 8081
#其它配置...
---
spring:
config:
activate:
on-profile: prod #设置生产环境
server:
port: 8082
#其它配置...
2.2、YAML 多文件版
公共环境配置:application.yml
spring:
profiles:
active: prod #启动指定环境
开发环境配置:application-dev.yml
server:
port: 8080
#其它配置...
测试环境配置:application-test.yml
server:
port: 8081
#其它配置...
生产环境配置:application-prod.yml
server:
port: 8082
#其它配置...
2.3、Properties 多文件版
公共环境配置:application.properties
#启动指定环境
spring.profiles.active=prod
开发环境配置:application-dev.properties
server.port=8080
#其它配置...
测试环境配置:application-test.properties
server.port=8081
#其它配置...
生产环境配置:application-prod.properties
server.port=8082
#其它配置...
2.4、多环境开发控制
当 Maven 与 Spring Boot 同时对多环境进行控制时,以 Mavn 为主,Spring Boot 使用 @..@
占位符读取 Maven 对应的配置属性值。
Maven 中设置多环境属性:
<profiles>
<!--开发环境-->
<profile>
<id>dev_env</id>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<!--测试环境-->
<profile>
<id>test_env</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<!--生产环境-->
<profile>
<id>prod_env</id>
<properties>
<profile.active>prod</profile.active>
</properties>
<!--激活环境-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
Spring Boot 配置文件中引用 Maven 属性:
spring:
profiles:
active: @profile.active@ #启动指定环境