ANT(1.6)高級特性:模塊化
<>
1. Property
Property Task除了能夠定義單個(gè)的屬性,還可以從一個(gè)屬性定義文件定義多個(gè)property。把公用的屬性放到屬性文件中,各個(gè)build.xml中都載入此屬性文件,就可以避免在每個(gè)build.xml中重復定義這些屬性。
2. AntCall, Ant和SubAnt
AntCall可以理解為簡(jiǎn)單的函數調用。舉一個(gè)例子就清楚了:
<target name=”commonTarget”>
<echo message=”${test.param}” />
</target>
<target name=”callingTarget”>
<antcall target="commonTarget">
<param name="test.param" value="Modulation" />
</antcall>
</target>
輸出結果如下圖所示:
從上面的例子可以看到,指明要調用的target,再通過(guò)<param>指明調用參數;在被調用的Target中,通過(guò)與引用property類(lèi)似的方式即可引用param的值。
至于Ant Target,也是調用別的Target,不過(guò)那個(gè)Target可以是在另外一個(gè)ant 文件中。至于SubAnt是什么?還不太清楚。
3. MacroDef
AntCall很好用,不過(guò)當參數很多時(shí)要寫(xiě)很多的<param name=”” value=”” />起來(lái)很麻煩,如果你想偷懶,用MacroDef就行了。下面把上面的例子用MacroDef重寫(xiě):
<macrodef name="showModule">
<attribute name="test.param" default="NOT SET"/>
<sequential>
<echo message="@{test.param}" />
</sequential>
</macrodef>
<target name="testMacro">
<showModule test.param="Modulation" />
</target>
運行結果
從輸出可以看出,我們可以象系統提供的其他Task一樣引用showModule,的確簡(jiǎn)潔多了。定義一個(gè)Macro,首先定義此宏的attribute,包括attribute的name, default;然后在<sequential>標簽中定義此宏的所有操作。注意對attribute的引用是@{attr-name}!實(shí)際上,Ant還允許在attribute后面定義一組element,達到極高的動(dòng)態(tài)性。
4. Import
<antcall>和<marcodef>可以達到類(lèi)似函數的效果,但是調用者和被調用者還是必須在同一個(gè)文件中。Ant從1.6開(kāi)始引入Import Task,可以真正的實(shí)現代碼重用:屬性,Task 定義,Task, Macro。一個(gè)簡(jiǎn)單的例子:
common.xml:
<?xml version="1.0" ?>
<project>
<property name="project.name" value="Ant Modulazation" />
<target name="commonTarget">
<echo message="${test.param}" />
</target>
<macrodef name="showModule">
<attribute name="test.param" default="NOT SET"/>
<sequential>
<echo message="@{test.param}" />
</sequential>
</macrodef>
</project>
call.xml:
<?xml version="1.0" ?>
<project name="testCommon" default="callingTarget">
<import file="common.xml" />
<target name="callingTarget">
<antcall target="commonTarget">
<param name="test.param" value="Modulation" />
</antcall>
</target>
<target name="testMacro">
<showModule test.param="Modulation" />
</target>
</project>
運行結果:
注意:在common.xml中,不能對project元素設置屬性;另外,不要試圖使用重名的property,或target以獲取覆蓋的效果,因為Ant畢竟不是編程語(yǔ)言!
聯(lián)系客服