SpringBoot 多Profile使用与切换

原文

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

【1】多Profile文件

文件名格式:

application-{profile}.properties
  • 1

默认使用application.properties配置文件。

如下所示,分别创建application-dev.properties和application-prod.properties文件。

  • application-dev.properties
server.port=8082
  • 1
  • application-prod.properties
server.port=8083
  • 1
  • application.properties
server.port=8081
spring.profiles.active=dev
  • 1
  • 2

在application.properties中**了application-dev.properties配置文件。

SpringBoot 多Profile使用与切换


【2】yml多文档快

yml文件中支持使用三个短横线分割文档块的方式。

server:
  port: 8082
spring:
  profiles:
    active: dev
---
spring:
  profiles: dev
server:
  port: 8083
---
spring:
  profiles: prod
server:
  port: 8084
---
spring:
  profiles: default
server:
  port: 80
---
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

其中default表示未指定时默认使用的配置。

SpringBoot 多Profile使用与切换


【3】**指定配置方式

① 配置文件方式

spring:
  profiles:
    active: dev
  • 1
  • 2
  • 3

spring.profiles.active=dev
  • 1

② 命令行方式

在打包后运行的时候,添加参数:

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar 
--spring.profiles.active=dev;
  • 1
  • 2

③ 编辑Configurations,填写命令行参数或虚拟机参数

SpringBoot 多Profile使用与切换

1、springboot优先读取application.properties中文件的内容。
2、application.properties与其他环境中出现相同的内容,以指定的环境中的内容为准。
3、如果不指定spring.profiles.active ,则只读取application.properties中的内容。