SpringBoot profile配置

13

SpringBoot profile配置

author: histonevon@zohomail.com

date: 09/07/2021

[TOC]

功能

  • 动态配置切换
  • profile配置方式
    • 多profile文件方式
    • yml多文档方式
  • profile激活方式
    • 配置文件
    • 虚拟机参数
    • 命令行参数

profile配置方式

多profile文件方式

  • src/main/resources 下创建三个文件,并写入配置(写法同 application.properties

    • application-dev.properties 开发配置
    • application-test.properties 测试配置
    • application-pro.properties 生产配置
  • application.properties 中添加如下语句

    spring.profiles.active=dev # 表示激活开发配置
    

yml多文档方式

  • application.yml 文件中,使用三个减号分隔:---
  • 以下示例为激活生产配置
---
server:
  port: 8081

spring:
  config:
    activate:
      on-profile: dev
---
server:
  port: 8082

spring:
  config:
    activate:
      on-profile: test
---
server:
  port: 8083

spring:
  config:
    activate:
      on-profile: pro
---
spring:
  profiles:
    active: pro # 激活生产配置

profile激活方式

配置文件

  • 上面的激活方式

虚拟机参数

  • 在IDEA中选择 Edit Configuration

    image-20210907143723288

  • VM options 中填入

    -Dspring.profiles.active=test # 激活测试配置
    

    image-20210907143827850

命令行参数

  • Program arguments 中填入

    --spring.profiles.active=pro # 激活生产配置
    

    image-20210907144122602

  • 或者不依赖IDEA,打包成jar包后,在命令行运行时添加参数

    --spring.profiles.active=pro # 激活生产配置
    

    image-20210907145639977