springboot项目不同环境的配置读取方式
作者:北极熊不在北极
SpringBoot支持application.properties、application.yml、application.yaml三种配置文件类型,可同时存在并合并配置,配置文件的读取优先级为:application.properties > application.yml > application.yaml,不同位置的相同类型配置文件
一、首先我知道的是
springboot项目可以使用如下3种类型配置文件,并且可以同时存在。
springboot读取到的不同配置内容会进行合并,如果有配置了相同的配置项,则以如下优先顺序进行生效:
application.properties > application.yml > application.yaml
二、相同类型配置文件
放在不同位置,生效优先顺序如下:
- 1级: springboot-demo.jar同级目录: config/application.yml[最高)
- 2级: springboot-demo.jar同级目录 : application.yml
- 3级: classpath: config/application.yml
- 4级: classpath: application.yml
三、在一个配置文件中
也可以配置如下不同的环境配置
#设置启用的环境
spring:
profiles:
active: dev
---
spring:
profiles: dev
server:
port: 81
---
spring:
profiles: test
server:
port: 82
---
spring:
profiles: pro
server:
port: 83四、在application.yml文件中可以读取到pom文件中的配置
可用于配置当前环境
#设置启用的环境
spring:
profiles:
active: ${profile.active}
---
spring:
profiles: dev
server:
port: 81
---
spring:
profiles: test
server:
port: 82
---
spring:
profiles: pro
server:
port: 83pom文件中的配置如下:
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>utf-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin><profiles>
<!--dev环境-->
<profile>
<id>dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<!--test环境-->
<profile>
<id>test</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
<!--pro环境-->
<profile>
<id>pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
