基本概念說明(resources、filter和profile):
1.profiles定義了各個環境的變量id
2.filters中定義了變量配置文件的地址,其中地址中的環境變量就是上面profile中定義的值
3.resources中是定義哪些目錄下的文件會被配置文件中定義的變量替換,一般我們會把項目的配置文件放在src/main/resources下,像db,bean等,里面用到的變量在打包時就會根據filter中的變量配置替換成固定值
在我們平常的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} --> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <filters> <filter>config-dev.properties</filter> </filters> </build> </profile> <profile> <id>test</id> <build> <filters> <filter>config-dev.properties</filter> </filters> </build> </profile> <profile> <id>product</id> <build> <filters> <filter>config-product.properties</filter> </filters> </build> </profile> </profiles>
三,使用:
開發環境:
filter是在maven的compile階段執行過慮替換的,所以只要觸發了編譯動作即可,如果像以前一樣正常使用發現沒有替換,則手工clean一下工程(eclipse -> Project -> Clean)【這里你應該要安裝上maven插件,因為替換是maven做的,不是eclipse做的,所以這里的clean應當是觸發了maven的compile】,然后在Tomcat上也右鍵 -> Clean一下即可,然后你去tomcat目錄下會發現你的工程的資源文件里面的${key}被替換為對應的config-xx的值了
如果上面還不行,那么就使用maven插件或者手工控制台下打maven編譯命令吧
因為pom.xml中設置了dev為默認激活的,所以默認會把config-dev拿來進行替換${key}
測試環境
手工編譯,打包:maven clean install -Ptest -- 激活id="test"的profile
生產環境
手工編譯,打包:maven clean install -Pproduct -- 激活id="product"的profile