深入理解maven與應用(二):靈活的構建
一個優秀的構建系統必須足夠靈活,應該能夠讓專案在不同的環境下都能成功構建。maven為了支援構建的靈活性,內建了三大特性,即:屬性、profile和資源過濾。
1、maven屬性
maven屬性分6類:
1、內建屬性:如${basedir}表示專案根目錄,${version}表示專案版本
2、POM屬性:使用者可以引用pom檔案中對應的值。如:
${basedir} 專案根目錄
${project.build.directory} 構建目錄,預設為target
${project.build.outputDirectory} 構建過程輸出目錄,預設為target/classes
${project.build.finalName} 產出物名稱,預設為${project.artifactId}-${project.version}
${project.packaging} 打包型別,預設為jar
${project.xxx} 當前pom檔案的任意節點的內容
3、自定義屬性:使用者可以在pom的<properties>元素下自定義maven屬性。
4、setting屬性:使用者可以使用以settings開頭的屬性引用settings.xml中xml元素的值,如${settings.localRepository}指向使用者本地倉庫的地址。
5、java系統屬性:maven可以使用當前java系統的屬性,如${user.home}指向了使用者目錄。
6、環境變數屬性:所有環境變數都可以使用以env.開頭的屬性。如:${env.JAVA_HOE}。
2、資源過濾
這裡所謂的資源:也就就是指src/main/resources和src/test/resources檔案下的所有檔案,預設情況下,這些檔案會被複制到classpath下面,即target/classes下面。
所謂資源過濾,就是過濾這些資料夾下面的檔案裡面的內容,看裡面的maven變數是否需要替換。預設情況下,只有pom.xml裡面的變數才會被替換,資原始檔是不會被過濾的,但是可以設定,如下:
<build> <finalName>agentmanager</finalName> <sourceDirectory>src/main/java</sourceDirectory> <resources> <!-- 控制資原始檔的拷貝 --> <resource> <directory>src/main/resources</directory> <excludes> <exclude>**/jre.zip</exclude> <exclude>**/jre.tar</exclude> <exclude>agentmanager.jsmooth</exclude> <exclude>assembly.xml</exclude> </excludes> <targetPath>${project.build.directory}</targetPath> </resource> <resource> <directory>src/main/resources/conf</directory> <targetPath>${basedir}/conf</targetPath> <filtering>true</filtering> </resource> </resources> </build>
如jdbc.properties
jdbc.driverClassName=${db.driver}
jdbc.url=${db.url}
jdbc.username=${db.user}
jdbc.password=${db.pwd}
profile檔案
<profiles> <profile> <id>dev</id> <properties> <db.driver>oracle.jdbc.driver.OracleDriver</db.driver> <db.url>jdbc:oracle:thin:@10.252.48.3:1521:dbname</db.url> <db.user>username</db.user> <db.pwd>userpwd</db.pwd> </properties> </profile> <profile> <id>test</id> <properties> <db.driver>oracle.jdbc.driver.OracleDriver</db.driver> <db.url>jdbc:oracle:thin:@10.252.48.3:1521:testdbname</db.url> <db.user>testusername</db.user> <db.pwd>testuserpwd</db.pwd> </properties> </profile> </profiles>
在構建時可以使用-P引數啟用一個或多個profile,多個之間用逗號分隔
如 mvn clean install -Pdev
3、maven profile
上面例子應該可以看出profile是做什麼的,其實就相當於定義了一系列的profile變數,在具體構建時可用使用其中的某個profile去變數替換資原始檔。
啟用profile的方式有很多,如命令列啟用(上面),settings檔案顯式啟用、系統屬性啟用、作業系統環境啟用、預設啟用、檔案存在與否啟用等,具體可以參考官網資料。
3.1 profile的種類
根據需要,可以在以下檔案宣告profile。
1、pom.xml 針對當前專案
2、使用者 settings.xml 使用者目錄下的.m2/settings.xml, 對當前使用者的所有專案有效。
3、全域性 settings.xml 即maven安裝目錄下的conf/settings.xml。對本機上的所有專案有效。
4、web資源過濾
在maven的web專案裡面,除了上面所說的資原始檔(src/main/resources)之外,還有一類叫做web資源目錄,即src/main/webapp下面的js、css等等。預設情況下,這些目錄是不被資源過濾的,開啟的命令如下:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
<includes>
<include>**/*.css</include>
<include>**/*.js</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>