SpringBoot多环境配置profiles

1.什么是Profiles?
Profile 可以让 Spring 对不同的环境提供不同配置的功能,可以通过激活、指定参数等方式快速切换环境

2.SpringBoot的主配置文件application.yml的存放路径共有4种

  1. file:config/
  2. file:/
  3. classpath:config/
  4. classpath:/
    优先级从高到底
    在这里插入图片描述

2 多Profile文件形式
在进行实际开发的时候,分为本地环境、测试环境和生产环境,这就需要配置多个配置文件,如端口号等等,我们当然可以每更换一个环境就改一次配置,但是十分繁琐

这个时候就可以多设置几个配置文件,文件名格式可以是 application-{profile}.properties/yml,但默认使用的主配置文件 application.properties

我们可以在主配置文件中随时切换成其他配置文件。比如我创建了三个配置文件

application.properties:主配置文件
application-dev.properties:开发环境配置文件
application-test.properties:测试环境配置文件
application.prop-properties:生产环境配置文件
为每个配置文件设置不同的端口号:

application-dev.properties
开发环境 server.port=8082

application-test.properties
测试环境server.port=8083

application.prop-properties
生产环境server.port=8084

这个时候需要里面切换到开发环境,则可以在主配置文件中使用如下指令

本地环境 server.port=8081
切换到开发环境 spring.profiles.active=dev

  1. yml多文档块方式
    在 xxx.yml 配置文件中,每使用一个 — 分割代表分割成了一个文档块,可以在不同的文档块中进行配置,并在第一个文档块对配置进行切换

配置一个多文档块的 yml 文件

server:
    port: 8081
spring:
    profiles:
        active: test	# 切换配置
---
# 开发环境
server:
    port: 8082
spring:
    profiles: dev
---
# 测试环境
server:
    port: 8083
spring:
    profiles: test
---
# 生产环境
server:
    port: 8084
spring:
    profiles: prop

此时需要在第一个多文档块中切换配置,当切换到某一个配置后,该配置(文档块)下的所有配置都能生效

4激活指定的profile
①. 在配置文件中激活
对于 xxx.properties 形式的配置,在主配置文件中使用

# 切换到xxx配置
spring.profiles.active=xxx

对应 xxx.yml 形式的配置,在第一个代码块中使用

# 切换到xxx配置
spring:
    profiles:
        active: xxx

②. 使用命令行激活
我们可以在 IDEA 的 Program arguments 进行设置 --spring-profiles.active=dev
在这里插入图片描述
我们也可以配置 JVM 的参数,具体是在 IDEA 的 VM options 设置 -Dspring.profiles.active=prop
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mmmmmlj/article/details/108955284