通过maven profile 打包指定环境配置

背景

最近换了个新公司接手了一个老项目,然后比较坑的是这个公司的项目都没有没有做多环境打包配置,每次发布一个环境都要手动的去修改配置文件。今天正好有空就来配置下。

解决这个问题的方式有很多,我这里挑选了一个个人比较喜欢的方案,通过 maven profile 打包的时候按照部署环境打包不同的配置,下面说下具体的操作

配置不同环境的配置文件

建立对应的环境目录,我这里有三个环境分别是,dev/test/pro 对应 开发/测试/生产。建好目录后将相应的配置文件放到对应的环境目录中

图片

配置 pom.xml 设置 profile

这里通过 activeByDefault 将开发环境设置为默认环境。如果你是用 idea 开发的话,在右侧 maven projects > Profiles 可以勾选对应的环境。

<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>pro</id>
        <properties>
            <profiles.active>pro</profiles.active>
        </properties>
    </profile>
</profiles>

打包时根据环境选择配置目录

这个项目比较坑,他把配置文件放到了webapps/config下面。所以这里打包排除 dev/test/pro 这三个目录时候,不能使用exclude去排除,在尝试用 warSourceExcludes 可以成功。之前还试过 packagingExcludes 也没有生效,查了下资料发现 packagingExcludes maven 主要是用来过滤 jar 包的。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <warSourceExcludes>
            config/test/**,config/pro/**,config/dev/**
        </warSourceExcludes>
        <webResources>
            <resource>
                <directory>src/main/webapp/config/${profiles.active}</directory>
                <targetPath>config</targetPath>
                <filtering>true</filtering>
            </resource>
        </webResources>
    </configuration>
</plugin>

最后根据环境打包

## 开发环境打包
mvn clean package -P dev

## 测试环境打包
mvn clean package -P test

## 生产环境打包
mvn clean package -P pro

执行完后发现 dev 目录下的文件已经打包到 config下

图片

启动项目

我在启动项目的时候,死活启动不了。后来对比了前后的 target 目录发现子项目的 jar 包有些差异,经过多次尝试后。将所有子项目下 target 项目重新删除 install 最后成功启动。

原文地址:https://www.cnblogs.com/lionsblog/p/10214751.html