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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM