-
2009-06-11
Ant雕虫技
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://dreamhead.blogbus.com/logs/40849752.html
当构建脚本变得复杂,分离变化这样编程思路同样可以应用其上。
下面是一份简化过的构建脚本:
<project basedir="." default="war" name="my_project">
<target name="config">
<property name="prop" value="prop_value"/>
</target>
<target name="build" depends="config">
<echo message="build ${prop}"/>
</target>
<target name="war" depends="build">
<echo message="war ${prop}"/>
</target>
</project>
世界变化快,新需求来了,我们要进行一些安全设制。这份构建脚本即要支持安全版本的构建,也要支持非安全的构建。
冲入大脑的第一个想法自然是重写一个支持安全war任务。不过,稍加分析不难发现,安全版本和非安全版本的策略差异最终体现出来就只是一些属性的差异,也就是从config开始,二者就开始走上了两条不同的路。如果构建一个安全的war任务,那意味着,我们也同样构建一个安全的build任务,一个安全的config任务也是不可或缺的。这是一个经过简化的构建脚本,在真实的项目里面,task数量不会这么少,task执行的任务不会这么简单的。顺着这个思路想下去,得到就是一个让人抓狂的结果。
策略的差异只是影响到一些属性,如果根据不同的策略,只是配置相关属性,似乎生活就可以轻松许多。下面就是按照这种思路编写的一个新脚本:
<project basedir="." default="war" name="my_project">
<target name="sec">
<property name="isSec" value="true"/>
</target>
<target name="nosec">
<property name="isNoSec" value="true"/>
</target>
<target name="defaultStrategy">
<condition property="isSec">
<not>
<isset property="isNoSec"/>
</not>
</condition>
</target>
<target name="configSec" depends="defaultStrategy" if="isSec">
<property name="prop" value="sec_value"/>
</target>
<target name="configNoSec" depends="defaultStrategy" if="isNoSec">
<property name="prop" value="no_sec_value"/>
</target>
<target name="config" depends="configSec, configNoSec"/>
<target name="build" depends="config">
<echo message="build ${prop}"/>
</target>
<target name="war" depends="build">
<echo message="war ${prop}"/>
</target>
</project>
需要基于安全的版本时,
ant sec war
而非安全版本是
ant nosec war
这样,属性的配置和真正任务就成了两个独立的维度,不必因为属性的变动对任务进行大幅度修改。
在这个例子里面,我们用到了一些ant的特性,比如像configSec、configNoSec这样基于条件执行的任务,比如像defaultStrategy任务中,在没有指定参数时选择缺省的策略。
引用地址:








评论