现在的位置: 首页 > 综合 > 正文

ANT(1.6)高级特性:模块化

2013年08月09日 ⁄ 综合 ⁄ 共 2454字 ⁄ 字号 评论关闭

Ant作为一种编程的辅助工具,可以看作与脚本一个级别的东西。写一个build.xml,用它来帮助你干各种小杂活,应该是一件很简单的事情。但是如果是一个很大的工程呢?如果你需要写很多的build.xml,那么与其他脚本语言一样,由于维护和代码重用的压力,你必须考虑到一个因素:模块化。在TheServerSide上面有一个讨论是关于Ant1.6与模块化的:Ant 1.6 - finally a real build tool http://www.theserverside.com/news/thread.tss?thread_id=25195。到1.6版为止,Ant已经提供了很多Task,可以帮助实现Ant脚本的模块化。

 

1.       Property

Property Task除了能够定义单个的属性,还可以从一个属性定义文件定义多个property。把公用的属性放到属性文件中,各个build.xml中都载入此属性文件,就可以避免在每个build.xml中重复定义这些属性。

 

2.       AntCall, AntSubAnt

AntCall可以理解为简单的函数调用。举一个例子就清楚了:

    

<target name=”commonTarget”>

       <echo message=”${test.param}” />

</target>

 

<target name=”callingTarget”>

       <antcall target="commonTarget">

              <param name="test.param" value="Modulation" />

       </antcall>

</target>

    输出结果如下图所示:

 

 


从上面的例子可以看到,指明要调用的target,再通过 指明调用参数;在被调用的Target中,通过与引用property类似的方式即可引用param的值。

至于Ant Target,也是调用别的Target,不过那个Target可以是在另外一个ant 文件中。至于SubAnt是什么?还不太清楚。

 

3.       MacroDef

AntCall很好用,不过当参数很多时要写很多的 起来很麻烦,如果你想偷懒,用MacroDef就行了。下面把上面的例子用MacroDef重写:

      

       <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,的确简洁多了。定义一个Macro,首先定义此宏的attribute,包括attributename, default;然后在标签中定义此宏的所有操作。注意对attribute的引用是@{attr-name}!实际上,Ant还允许在attribute后面定义一组element,达到极高的动态性。

 

4.       Import

可以达到类似函数的效果,但是调用者和被调用者还是必须在同一个文件中。Ant1.6开始引入Import Task,可以真正的实现代码重用:属性,Task 定义,Task Macro。一个简单的例子:

 

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毕竟不是编程语言

 

 

抱歉!评论已关闭.