1.Ant是什么?Apache Ant 是一个基于 Java的生成工具。生成工具在软件开发中用来将源代码和其他输入文件转换为可执行文件的形式(也有可能转换为可安装的产品映像形式)。随着应用程序的生成过程变得更加复杂,确保在每次生成期间都使用精确相同的生成步骤,同时实现尽可能多的自动化,以便及时产生一致的生成版本。
2.Ant的使用
运行Ant非常简单,正确地安装Ant后,只要输入ant就可以了。
1) 没有指定任何参数时,Ant会在当前目录下查询build.xml文件。如果找到了就用该文件作为buildfile。如果使用 -find 选项。Ant就会在上级目录中寻找buildfile,直至到达文件系统的根。要想让Ant使用其他的buildfile,可以用参数 -buildfile file,这里file指定了你想使用的buildfile。2) 可以指定执行一个或多个target。当省略target时,Ant使用标签的default属性所指定的target。
命令行选项总结:ant [options] [target [target2 [target3] ...]]Options:-help print this message-projecthelp print project help information-version print the version information and exit-quiet be extra quiet-verbose be extra verbose-debug print debugging information-emacs produce logging information without adornments-logfile file use given file for log output-logger classname the class that is to perform logging-listener classname add an instance of class as a project listener-buildfile file use specified buildfile-find file search for buildfile towards the root of the filesystem and use the first one found
-Dproperty=value set property to value
# 例子ant (使用当前目录下的build.xml运行Ant,执行缺省的target)ant -buildfile test.xml (使用当前目录下的test.xml运行Ant,执行缺省的target)ant -buildfile test.xml dist (使用当前目录下的test.xml运行Ant,执行一个叫做dist的target)ant -buildfile test.xml -Dbuild=build/classes dist (使用当前目录下的test.xml运行Ant,执行一个叫做dist的target,并设定build属性的值为build/classes)
3.编写build.xml
Ant的buildfile是用XML写的。每个buildfile含有一个project。
buildfile中每个task元素可以有一个id属性,可以用这个id值引用指定的任务。这个值必须是唯一的。
3.1 Projectsproject有下面的属性:Attribute Required Descriptionname No 项目名称.default Yes 当没有指定target时使用的缺省targetbasedir No 用于计算所有其他路径的基路径。该属性可以被basedir property覆盖。当覆盖时,该属性被忽略。如果属性和basedir property都没有设定,就使用buildfile文件的父目录。
个项目可以定义一个或多个target。一个target是一系列你想要执行的。执行Ant时,你可以选择执行那个target。当没有给定target时,使用project的default属性所确定的target。3.2 Targets
一个target可以依赖于其他的target。例如,你可能会有一个target用于编译程序,一个target用于生成可执行文件。你在生成可执行文件之前必须先编译通过,所以生成可执行文件的target依赖于编译target。Ant会处理这种依赖关系。
然而,应当注意到,Ant的depends属性只指定了target应该被执行的顺序-如果被依赖的target无法运行,这种depends对于指定了依赖关系的target就没有影响。
Ant会依照depends属性中target出现的顺序(从左到右)依次执行每个target。然而,要记住的是只要某个target依赖于一个target,后者就会被先执行。假定我们要执行target D, 则会先执行A,然后B,然后C,最后D被执行。一个target只能被执行一次,即使有多个target依赖于它(看上面的例子)。
target有下面的属性:Attribute Required Description
name Yes target的名字D
depends No 用逗号分隔的target的名字列表,也就是依赖表。
if No 执行target所需要设定的属性名。
unless No 执行target需要清除设定的属性名。
description No 关于target功能的简短描述。
3.3 Tasks
一个task是一段可执行的代码。一个task可以有多个属性(如果你愿意的话,可以将其称之为变量)。属性只可能包含对property的引用。这些引用会在task执行前被解析。下面是Task的一般构造形式:这里name是task的名字,attributeN是属性名,valueN是属性值。有一套内置的(built-in)task,以及一些可选task,但你也可以编写自己的task。所有的task都有一个task名字属性。Ant用属性值来产生日志信息。
3.4 Properties一个project可以有很多的properties。可以在buildfile中用property task来设定,或在Ant之外设定。一个property有一个名字和一个值。property可用于task的属性值。这是通过将属性名放在"${"和"}"之间并放在属性值的位置来实现的。例如如果有一个property builddir的值是"build",这个property就可用于属性值:${builddir}/classes。这个值就可被解析为build/classes。