SpringBoot系列之profiles配置多环境用法介绍

SpringBoot系列之profles配置多环境用法介绍

继续上篇博客SpringBoot系列之集成profles配置多环境
之后,继续写一篇博客进行补充

写Spring项目时,在测试环境是一套数据库配置,到了生产环境都要将配置改过来,如果改错了就一堆坑来了,所以Springboot提供了多环境配置,可以实现多种环境配置的动态切换,上篇博客介绍的基于maven和Springboot的profile的使用,本博客补充介绍一下Springboot profile使用的一些细节

1、多Profile文件

在编写profile文件的时候,文件命名可以是application-{profile}.properties/yml,Springboot项目启动时候默认加载的是application.properties/yml的配置

一般来说的多环境配置,显然名称是不固定的

  • application-dev(开发环境)
  • application-test(测试环境)
  • application-uat(预发布)
  • application-prod(生产环境)

具体使用哪个配置,可以在默认配置文件里配置,如使用dev配置文件的:

yml写法:

spring:
  profiles:
    active: dev

properties写法:

spring.profiles.active=dev

2、yaml多文档块写法

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

使用的是dev的配置
在这里插入图片描述
当然,你不喜欢这种写法,你自己新建一个yml配置文件也是可以的
在这里插入图片描述

3、maven配置文件写法

profile的配置还可以写在maven配置里

<profiles>
        <profile>
            <id>dev</id>
            <properties>
                <activatedProperties>dev</activatedProperties>
                <project.packaging>jar</project.packaging>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <activatedProperties>test</activatedProperties>
                <project.packaging>jar</project.packaging>
            </properties>
        </profile>
        <profile>
            <id>uat</id>
            <properties>
                <activatedProperties>uat</activatedProperties>
                <project.packaging>jar</project.packaging>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <activatedProperties>prod</activatedProperties>
                <project.packaging>jar</project.packaging>
            </properties>
        </profile>
    </profiles>


具体使用参考我之前博客SpringBoot系列之profles配置多环境(篇一)

4、profile多环境动态启动方式

ok,配置了profile之后,启动的方式介绍一下

  • 1)配置文件设置
spring:
  profiles:
    active: dev
  • 2)application的Configurations配置
    在这里插入图片描述
  • 3)jar启动时候配置
    先package,打成jar
    在这里插入图片描述
java -jar springboot-profile-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

在这里插入图片描述

  • 4)虚拟机参数设置
    ok,也可以通过虚拟机参数配置
-DSpring.profiles.active=dev

在这里插入图片描述

发布了347 篇原创文章 · 获赞 1776 · 访问量 126万+

猜你喜欢

转载自blog.csdn.net/u014427391/article/details/102931424