侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 747 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

SpringBoot(7)之Profile多环境配置

zze
zze
2018-01-24 / 0 评论 / 0 点赞 / 565 阅读 / 1586 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

概述

Profile 是 Spring 提供的一项能使配置更清晰便捷的功能,它能够对不同环境提供不同配置功能的支持,可以通过激活指定环境、指定参数等方式快速切换环境。

使用

Profile 的使用有如下两种方式。

方式一:多 Profile 文件

格式:

application-{profile}.properties/yml
例:
application-dev.properties/yml
application-prod.properties/yml

现有如下配置文件:

# application.yml
spring:
  profiles:
    active: default
# application-dev.yml
server:
  port: 8081
# application-test.yml
server:
  port: 8082

因 SpringBoot 默认使用的配置文件为 application.yml ,所以需要通过 application.yml 中的 spring.profiles.active 属性来指定当前环境,默认不指定时为 default ,若想要切换到 test 环境,直接指定该属性值为 test 即可。

方式二:YAML 文档块

使用 YAML 配置文件时可以通过 --- 将一个文件分为若干个文档块,可以在每个文档块中做指定环境的配置。默认加载第一个文档快,所以可以在第一个文档块中指定所激活的环境。

# application.yml
# document1 start
spring:
  profiles:
    active: default
# document1 end
---
# document2 start
server:
  port: 8081
spring:
  profiles: test
# document2 end
---
# document3 start
server:
  port: 8082
spring:
  profiles: dev
# document3 end

除了上述所说的在默认全局配置文件中通过 spring.profiles.active 属性来激活指定环境外,还可以通过以下方式激活指定环境:

通过配置命令行参数( Program arguments )指定 --spring.profiles.active=[环境]

打包后通过命令行方式指定 java -jar springboot_helloworld-1.0-SNAPSHOT.jar --spring.profiles.active=[环境]

通过虚拟机参数(VM options)指定 -Dspring.profiles.active=dev

0

评论区