springboot多环境配置

转载自:www.javaman.cn

前言

在实际项目研发中,需要针对不同的运行环境,如开发环境、测试环境、生产环境等,每个运行环境的数据库...等配置都不相同,每次发布测试、更新生产都需要手动修改相关系统配置。这种方式特别麻烦,费时费力,而且出错概率大。

Spring Boot为我们提供了更加简单方便的配置方案来解决多环境的配置问题。

spring profile配置

<!-- Maven控制Spring Profile -->
<profiles>
     <!--默认开启dev-->
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <profile.active>dev</profile.active>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <profile.active>prod</profile.active>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <profile.active>test</profile.active>
            </properties>
        </profile>
    </profiles>

resources 配置

<build>
        <finalName>${project.artifactId}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!--先排除所有的配置文件-->
                <excludes>
                    <exclude>application*.yml</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <!--引入所需环境的配置文件-->
                <filtering>true</filtering>
                <includes>
                    <!--加载配置文件-->
                    <include>application.yml</include>
                    <include>application-${profile.active}.yml</include>
                </includes>
            </resource>
            <resource>
                <directory>lib</directory>
                <targetPath>BOOT-INF/classes/lib/</targetPath>
                <includes>
                    <include>*.jar</include>
                </includes>
            </resource>
        </resources>
    </build>

多环境配置文件相关文件为:

  • application.yml 默认配置文件,需要通过此文件去引用其他配置文件

    一般来说开发会涉及到以下三种环境

  • application-dev.yml 开发环境

  • application-pro.yml 生产环境

  • application-test.yml 测试环境

application.yml配置

spring:
  profiles:
    active: @profile.active@

src/main/resources目录下创建多个不同环境的配置文件,命名为application-{profile}.yaml,例如:

  • application-dev.yaml
  • application-prod.yaml

在这些文件中,你可以设置相应环境的配置,如数据库连接、日志级别等。

image

在IDEA中,点击刷新即可选择编译环境

image

mvn打包命令

//打包生产环境
mvn clean install package -P pro -Dmaven.test.skip=true
//打包开发环境
mvn clean install package -P dev -Dmaven.test.skip=true
posted @ 2023-11-21 15:50  Java大师-  阅读(27)  评论(0编辑  收藏  举报