SpringBoot服务启动时指定环境配置文件

在日常开发中至少有三个环境,分别是开发环境(dev),测试环境(test),生产环境(prod)。不同的环境配置都不尽相同,如请求地址、用户名、密码等。

Spring Boot 对多环境整合已经有了很好的支持,能够在运行间、打包时自由切换环境。

创建配置文件

分别创建以下文件

  • application.yml
  • application-dev.yml
  • application-test.yml
  • application-prod.yml

application.yml 文件上默认的配置文件。

指定运行的环境

虽然创建了各个环境的配置文件,但是 Spring Boot 仍然不知道你要运行哪个环境,有以下两种方式指定:

配置文件中指定

在 application.yml 文件中指定,内容如下:

# 指定运行环境为测试环境
spring.profiles.active=test

如果没有指定运行的环境,Spring Boot 会默认加载 application.yml 文件,再去找 test 环境的配置文件。

运行 jar 的时候指定

Spring Boot 内置的环境切换能够在运行Jar包的时候指定环境,命令如下:

java -jar xxx.jar -Dspring.profiles.active=test

Maven 多环境配置

Maven 对于多环境的支持在功能方面更加强大,支持JDK版本、资源文件、操作系统等等因素来选择环境。

pom 文件中定义 profiles 配置:

<!-- 多环境配置方案 -->
<profiles>
    <profile>
        <!-- 不同环境的唯一ID -->
        <id>local</id>
        <activation>
            <!-- 默认激活环境 -->
            <activeByDefault>true</activeByDefault>
        </activation>
        <!-- 环境变量 -->
        <properties>
            <spring.profiles.active>local</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>dev</id>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>test</id>
        <properties>
            <spring.profiles.active>test</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

在使用 mvn 打包时,需要使用 -P 指定环境,如下:

mvn clean package -P test
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旷野历程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值