springboot配置之Profile多环境支持

时间:2022-07-23
本文章向大家介绍springboot配置之Profile多环境支持,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Profile是spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境。

  • 多profile文件格式: - 格式:appilication-[profile].properties application-dev.properties、appilication-prod.properties
  • 多profile文档块模式
  • 激活方式 - 命令行:--spring.profiles.active=dev - 配置文件:spring.profiles.active=dev - jvm参数:-Dspring.profiles.active=dev

说明:

第一种方式:

resources下有以下文件:

application.properties

server.port=8080
spring.profiles.active=dev

application-dev.propertites

server.port=8081

application-prod.properties

server.port=8082

这时我们启动springboot:确实切换到了application-dev环境

Tomcat started on port(s): 8081 (http) with context path ''

第二种方式:我们注释掉上述三个文件中的内容,并在application.yml中进行编写:

server:
  port: 8080
spring:
  profiles:
    active: prod
---
server:
  port: 8081
spring:
  profiles: dev
---
server:
  port: 8082
spring:
  profiles: prod

使用---可以区分环境块。并可以在主环境块中指定要使用的环境,启动springboot之后:

Tomcat started on port(s): 8081 (http) with context path ''

第三种方式:点击edit Configurations

(1)使用命令行参数

启动springboot:

Tomcat started on port(s): 8082 (http) with context path ''

(2) 使用虚拟机参数

Tomcat started on port(s): 8081 (http) with context path ''

当虚拟机参数和命令行参数都存在时:命令行参数的优先级比虚拟机参数优先级要高

(3)在运行jar包时:java -jar xxx.jar --spring.profiles.active=dev