Profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境。
一、多profile文件的形式。
文件名的格式:application-{profile}.properties/yml
;默认使用的是主配置文件:application.properties
- application.properties:主配置文件。
- application-dev.properties:开发环境配置文件。
- application-test.properties:测试环境配置文件。
- application-prod.properties:生产环境配置文件。
下面新建一个SpringBoot-04的项目,具体演示如下:
分别为每个配置文件设置设置不同的端口号进行测试:
主配值文件(application.properties)
server.port=8081
开发环境(application-dev.properties)
server.port=8082
生产环境(application-prod.properties)
server.port=8083
测试环境(application-test.properties)
server.port=8084
启动项目:
可以看到默认使用的是主配值文件配置的端口号。
在主配值文件中可以使用spring.profiles.active
进行环境的切换。
例如:在主配值文件application.properties中进行如下的配置切换到测试环境:
再次重启项目:
端口号就变成了8084!!!
二、yml的多文档块方式。
在yml 文件中完成所有 profile 的配置:(不同 的profile 之间用 — 进行分割)
server:
port: 8081
spring:
profiles:
active: prod
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: prod
---
server:
port: 8084
spring:
profiles: test
在第一个多文档块中进行切换配置,例如:
重新启动项目:
三、命令行方式。
(1)
在Program arguments
中配置参数:--spring.profiles.active=test
激活测试环境配置。
(2)
另外一种是:使用命令行启动项目,启动的同时可以指定激活的profile。
我把项目打包成jar包,复制到了E:\目录下。
切换到jar包所在目录:使用命令:
java -jar springboot-04-0.0.1-SNAPSHOT.jar --spring.profiles.active=test
(3)
也可以使用虚拟机参数:
-Dspring.profiles.active=dev
重启项目: