Ant作为一种编程的辅助工具,可以看作与脚本一个级别的东西。写一个build.xml,用它来帮助你干各种小杂活,应该是一件很简单的事情。但是如果是一个很大的工程呢?如果你需要写很多的build.xml,那么与其他脚本语言一样,由于维护和代码重用的压力,你必须考虑到一个因素:模块化。到1.6版为止,Ant已经提供了很多Task,可以帮助实现Ant脚本的模块化。 |
1. Property Property Task除了能够定义单个的属性,还可以从一个属性定义文件定义多个property。把公用的属性放到属性文件中,各个build.xml中都载入此属性文件,就可以避免在每个build.xml中重复定义这些属性。 |
2. AntCall, Ant和SubAnt AntCall可以理解为简单的函数调用。举一个例子就清楚了: <?xml version="1.0" ?> <project name="testAnt" default="commonTarget" > <target name="commonTarget"> <echo message="${test.param}"/> </target> <target name="callingTarget"> <antcall target="commonTarget"> <param name="test.param" value="Modulation" /> </antcall> </target> </project> 输出结果如下所示:>ant callingTarget
输出结果 写道
callingTarget:
commonTarget: [echo] Modulation 从上面的例子可以看到,指明要调用的target,再通过<param>指明调用参数;在被调用的Target中,通过与引用property类似的方式即可引用param的值。 |
3. MacroDef AntCall很好用,不过当参数很多时要写很多的<param name=”” value=”” />起来很麻烦,如果你想偷懒,用MacroDef就行了。下面把上面的例子用MacroDef重写: <?xml version="1.0" ?> <project name="testAnt" default="test" > <macrodef name="showModule"> <attribute name="v" default="NOT SET"/> <element name="some-tasks" optional="yes"/> <sequential> <echo>v is @{v}</echo> <some-tasks/> </sequential> </macrodef> <target name="test"> <showModule v="This is V"> <some-tasks> <echo>this is a test</echo> </some-tasks> </showModule> </target> </project> 运行结果:>ant
运行结果 写道
test:
[echo] v is This is V [echo] This is a test 从输出可以看出,我们可以象系统提供的其他Task一样引用test,的确简洁多了。定义一个Macro,首先定义此宏的attribute,包括attribute的name, default;然后在<sequential>标签中定义此宏的所有操作。注意对attribute的引用是@{attr-name}!实际上,Ant还允许在attribute后面定义一组element,达到极高的动态性。 |
4. Import <?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>
<?xml version="1.0" ?> <project name="testCommon" default="callingTarget"> <import file="common.xml" /> <target name="callingTarget" depends="testMacro"> <antcall target="commonTarget"> <param name="test.param" value="Modulation" /> </antcall> </target> <target name="testMacro"> <showModule test.param="Modulation" /> </target> </project>
运行结果如下:>ant
运行结果 写道
testMacro:
[echo] Modulation callingTarget: commonTarget: [echo] Modulation 注意:在common.xml中,不能对project元素设置属性;另外,不要试图使用重名的property,或target以获取覆盖 的效果,因为Ant毕竟不是编程语言。 |