多环境配置
多环境配置
在构建环境之初,一个很重要的特性就是根据不同的环境自动使用不同的配置文件,从而完成譬如测试数据库与开发数据库的动态切换。而spring.profiles.active
参数,那么application-{profile}.properties
文件,并且将其中内容提取出来用作创建java -jar xxx.jar --server.port=8888
命令,等价于我们在
指定环境启动
通过命令行来修改属性值是
在application-{profile}.properties
的格式,其中 {profile}
对应你的环境标识,比如:
application-dev.properties
:开发环境application-test.properties
:测试环境application-prod.properties
:生产环境
至于哪个具体的配置文件会被加载,需要在 application.properties
文件中通过 spring.profiles.active
属性来设置,其值对应配置文件中的 {profile}
值。如:spring.profiles.active=test
就会加载 application-test.properties
配置文件内容。
application.properties
中配置通用内容,并设置spring.profiles.active=dev
,以开发环境为默认配置application-{profile}.properties
中配置各个环境不同的内容- 通过命令行方式去激活不同环境的配置
注意,
spring:
profiles: "dev"
name: dev.didispace.com
---
spring:
profiles: "test"
name: test.didispace.com
---
spring:
profiles: "prod"
name: prod.didispace.com
而在本次
spring:
config:
activate:
on-profile: "dev"
name: dev.didispace.com
---
spring:
config:
activate:
on-profile: "test"
name: test.didispace.com
---
spring:
config:
activate:
on-profile: "prod"
name: prod.didispace.com
应用启动的时候,我们要加载不同的环境配置的参数不变,依然采用
java -jar myapp.jar -Dspring.profiles.active=dev
我们也可以将
spring:
profiles:
active: "dev"
默认配置文件
src/main/resources/application.properties
。关于
配置加载顺序
- 命令行中传入的参数。
SPRING_APPLICATION_JSON
中的属性。SPRING_APPLICATION_JSON
是以JSON 格式配置在系统环境变量中的内容。java:comp/env
中的JNDI
属性。Java 的系统属性,可以通过System.getProperties()
获得的内容。- 操作系统的环境变量
- 通过
random.*
配置的随机属性 - 位于当前应用
jar 包之外,针对不同{profile}
环境的配置文件内容,例如:application-{profile}.properties
或是YAML
定义的配置文件 - 位于当前应用
jar 包之内,针对不同{profile}
环境的配置文件内容,例如:application-{profile}.properties
或是YAML
定义的配置文件 - 位于当前应用
jar 包之外的application.properties
和YAML
配置内容 - 位于当前应用
jar 包之内的application.properties
和YAML
配置内容 - 在
@Configuration
注 解修改的类中,通过@PropertySource
注解定义的属性 - 应用默认属性,使用
SpringApplication.setDefaultProperties
定义的内容
优先级按上面的顺序有高到低,数字越小优先级越高。可以看到,其中第