會員註冊 / 登入  |  電腦版  |  Jump to bottom of page

軟體開發專案管理 Software Development Project Management » 利用filter讓Maven支援多重環境

發表人: andowson, 七段學員
2010-12-09 12:11:08
最近在研究Maven 3,針對公司的實際環境需求,尤其是有關資料庫JDBC連線的設定,需要將測試環境及上線環境作個區隔,我找到了篇不錯的文章
A Maven2 multi-environment filter setup
概念大致如下:
在pom.xml中針對filter的檔名加上一個${env}的環境變數,如:
<filters>

<filter>src/main/filters/filter-${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>


假設在src/main/resources/底下有個jdbc.properties,內容中有個變數是${db.host}

我們只要在src/main/filters/底下編輯三個檔案,將跟資料庫相關的設定寫在裡面
filter-dev.properties
db.host=127.0.0.1

filter-test.properties
db.host=192.168.1.33

filter-prod.properties
db.host=192.168.2.99

然後透過pom.xml中的profile設定
<!-- default environment -->

<properties>
<env>dev</env>
</properties>
<!-- profiles -->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>


日後執行mvn指令時只要加上-P參數來指定要用那個profile即可,如
mvn resources:resources <=產生開發環境用的jdbc.properties
mvn resources:resources -P test <=產生測試環境用的jdbc.properties
mvn resources:resources -P prod <=產生上線環境用的jdbc.properties




會員註冊 / 登入  |  電腦版  |  Jump to top of page