Springboot的application.properties或者application.yml文件的配置
1.关于多个配置环境的指定运行
我们在主配置文件编写的时候,文件名可以是:application-{profile}.properties/yml
两种文件的格式:
默认全局配置文件:
application.properties : k=v,或行内写法(k: v,[Set/List/数组] {map,对象类型的属性},并且 []可省,{}不能省)
application.yml : yaml ain't myarkup language ,不是一个标记文档
注意:1. k:空格v 2.通过垂直对齐 指定层次关系 3.默认可以不写引号; ""会将其中的转义符进行转义,其他不会
一般分为开发、测试、运行,命名要求要规范,下图有详细示例
1.1多个properties
默认使用application.properties的配置
目录可以如下:
如果要选择某一个具体的环境: application.properties中指定:spring.profiles.active=环境名
如果将application.properties注释掉,spring boot仍然会读取其他appilcation-环境名.properties中的配置。并且properties的优先级高于yml
1.2yml支持多文档块方式
通过—将文档分成多文档块:
注意格式首行同则相当于在同一目录
server:
port: 8081
spring:
profiles:
active: prod
#文档块一
---
server:
port: 8083
spring:
profiles: dev
#文档块二
---
server:
port: 8084
spring:
profiles: prod #指定属于哪个环境
#文档块三
1.3激活指定profile
配置文件中指定
使用spring.profiles.active激活指定profile
1.3.1 application.properties
1.3.2 application.yml
通过dev或prod指定当前运行的环境
程序参数指定
程序参数中添加–spring.profiles.acprotive激活指定profile
虚拟机参数指定
在VM options中添加-Dspring.profiles.active=dev
1.4 动态切换环境总结
i:通过运行参数指定环境
(1)STS(Eclipse) :Run Configuration - Argument - program Argument
--spring.profiles.active=环境名
(2)命令行方式:
java -jar 项目名.jar --spring.profiles.active=环境名
ii:通过vm参数指定环境
STS(Eclipse) :Run Configuration - Argument - VM
-Dspring.profiles.active=环境名
2.关于配置文件路径的读取顺序
–file:./config/
–file:./
–classpath:/config/
–classpath:/
优先级由高到底,高优先级的配置会覆盖低优先级的配置
SpringBoot会从这四个位置全部加载主配置文件,互补配置
最终读取文件运行情况:
项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置;(SpringBoot2.0版本之后指定文件与默认配置不会形成互补配置,只是指定文件中的配置生效)java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar –spring.config.location=文件路径