1. 程式人生 > >利用maven的resources、filter和profile實現不同環境使用不同配置檔案

利用maven的resources、filter和profile實現不同環境使用不同配置檔案

在我們平常的java開發中,會經常使用到很多配製檔案(xxx.properties,xxx.xml),而當我們在本地開發(dev),測試環境測試(test),線上生產使用(product)時,需要不停的去修改這些配製檔案,次數一多,相當麻煩。現在,利用maven的filter和profile功能,我們可實現在編譯階段簡單的指定一個引數就能切換配製,提高效率,還不容易出錯,詳解如下。 

一,原理: 

    利用filter實現對資原始檔(resouces)過濾 

maven filter可利用指定的xxx.properties中對應的key=value對資原始檔中的${key}進行替換,最終把你的資原始檔中的username=${key}替換成username=value 


    利用profile來切換環境 

maven profile可使用作業系統資訊,jdk資訊,檔案是否存在,屬性值等作為依據,來啟用相應的profile,也可在編譯階段,通過mvn命令加引數 -PprofileId 來手工啟用使用對應的profile 
結合filter和profile,我們就可以方便的在不同環境下使用不同的配製 

二,配製: 
在工程根目錄下新增3個配製檔案: 

    config-dev.properties  -- 開發時用 
    config-test.properties  -- 測試時用 
    config-product.properties -- 生產時用 

工程根目錄下的pom檔案中新增下面的設定: 


<build> 
<resources> 
<!-- 先指定 src/main/resources下所有檔案及資料夾為資原始檔 --> 
<resource> 
<directory>src/main/resources</directory> 
<includes> 
<include>**/*</include> 
</includes> 
</resource> 
<!-- 設定對auto-config.properties,jdbc.properties進行過慮,即這些檔案中的${key}會被替換掉為真正的值 --> 

<resource> 
<directory>src/main/resources</directory> 
<includes> 
<include>auto-config.properties</include> 
<include>jdbc.properties</include> 
</includes> 
<filtering>true</filtering> 
</resource> 
</resources> 
</build> 

<profiles> 
<profile> 
<id>dev</id> 

<!-- 預設啟用開發配製,使用config-dev.properties來替換設定過慮的資原始檔中的${key} --> 
<profile>