Spring不同环境加载不同配置文件 - resource & profile
我们在使用spring的时候,一般都会有不同的环境需要部署:开发环境、测试环境和生产环境,而不同的环境则会有不同的配置,比如数据库ip。解决这个问题,我所熟悉的有两种策略:
- springboot的profile参数配置
- pom文件的resource & profile配置
springboot的profile配置
Spring Profiles 允许用户根据环境配置来读取不同的配置文件(dev,test,online 等),可以通过激活、指定参数等方式快速切换环境。
profile多配置文件
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:
- application.properties:主配置文件
- application-dev.properties:开发环境
- application-test.properties:测试环境
- application-online.properties:生产环境
至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。
如:可以为每个配置文件设置不同的端口和数据库连接串
application-dev.properties
#开发环境
server.port = 8081
spring.datasource.durid.url=jdbc:mysql://aaaaaaa
application-test.properties
#测试环境
server.port = 8081
spring.datasource.durid.url=jdbc:mysql://bbbbbb
application-online.properties
#线上环境
server.port = 8081
spring.datasource.durid.url=jdbc:mysql://ccccccc
这个时候需要里面切换到开发环境,则可以在主配置文件中使用如下指令:
#本地环境
server.port = 8080
#切换到线上环境
spring.profiles.active=online
多配置文件
profile单配置文件
在 xxx.properties
配置文件中,每使用一个 --- 分割代表分割成了一个文档块,可以在不同的文档块中进行配置,并在第一个文档块对配置进行切换
配置一个多文档块的配置文件
server:
port: 8080
spring:
profiles:
active: test # 切换配置
---
# 开发环境
server:
port: 8081
spring:
profiles: dev
---
# 测试环境
server:
port: 8082
spring:
profiles: test
---
# 生产环境
server:
port: 8083
spring:
profiles: online
maven的profiles策略
maven的pom文件里面也有一个配置profiles的功能,这个profiles配合resources可以实现打包时根据配置的生效profiles的路径进行打包。
第一步:
创建配置文件,config目录下有三个文件夹:dev(开发)、test(测试)、online(生产)。
第二步:
配置pom文件
<!-- activation指定生效的profile -->
<profiles> <!-- profile组 -->
<profile> <!-- 一个profile -->
<id>dev</id> <!-- id,不能重复 -->
<activation> <!-- 指定生效的profile -->
<activeByDefault>true</activeByDefault>
</activation>
<properties> <!-- 该profile映射的路径 -->
<env.name>dev</env.name>
<resource.env.name>dev</resource.env.name>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env.name>${env}</env.name>
<resource.env.name>test</resource.env.name>
</properties>
</profile>
<profile>
<id>online</id>
<properties>
<env.name>${env}</env.name>
<resource.env.name>online</resource.env.name>
</properties>
</profile>
</profiles>
<build>
<!-- 配置文件打包时的映射路径,profiles.active获取当前生效的profile路径 -->
<resources> <!-- resources组 -->
<resource> <!-- 一个resource -->
<directory>src/main/resources</directory> <!-- 需要处理的路径 -->
</resource>
<resource>
<directory>src/main/resources/config/${resource.env.name}</directory> <!-- 打包文件所在的路径,profiles.active就是profiles里面生效的路径 -->
<targetPath>.</targetPath> <!-- 可有可无 -->
</resource>
</resources>
</build>
当工程本地启动时,会默认激活获取dev环境的参数配置,当线上或者测试环境启动时可以将环境标env作为参数传递进来,这样就可以达到灵活配置获取配置文件了。