使用MAVEN控制springboot项目的启动环境

image

通过IDEA的maven插件动态替换SpringBoot项目中的配置文件中的值,其它配置类似,比如数据库的密码等,可避免密码暴露

1、编辑pom.xml文件

    <profiles>
        <profile>
            <!-- 默认激活开发环境 -->
            <id>dev</id>
            <properties>
                <profiles.active>dev</profiles.active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>

        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
            </properties>
        </profile>
        
        <profile>
            <!-- 生产环境 -->
            <id>prod</id>
            <properties>
                <profiles.active>prod</profiles.active>
            </properties>
        </profile>
        
        <profile>
            <!-- 内网部署 -->
            <id>local</id>
            <properties>
                <profiles.active>local</profiles.active>
            </properties>
        </profile>
    </profiles>


    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!-- 关闭过滤 -->
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <!-- 引入所有 匹配文件进行过滤 -->
                <includes>
                    <include>application*</include>
                    <include>bootstrap*</include>
                    <include>banner*</include>
                </includes>
                <!-- 启用过滤 即该资源中的变量将会被过滤器中的值替换 -->
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

2、编辑配置

spring:
  profiles:
    # 激活环境配置
    active: @profiles.active@

至此既可使用Maven插件的按钮来控制启动环境了,注意配置文件中的实际值的优先级要大于通过按钮来替换的值的优先级

posted @ 2025-04-08 14:29  黄河大道东  阅读(22)  评论(0)    收藏  举报