1. 程式人生 > >通過maven profile 打包指定環境配置

通過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 最後成功啟動。