There is a long standing tradition in software of starting with "Hello World." We'll start our series of Ant tutorials with the same. I'm going to assume that you've successfully installed Ant and that you understand the basics of XML syntax. And just in case it makes a difference, I'm using version 1.5.1:
$ ant -version
Apache Ant version 1.5.1 compiled on October 2 2002
Copy the following lines into a file named "build.xml" (the default name assumed by ant).
<project default="hello">
<target name="hello">
<echo message="Hello, World"/>
</target>
</project>
And execute ant.
$ ant
Buildfile: build.xml
hello:
[echo] Hello, World
BUILD SUCCESSFUL
Total time: 2 seconds
Now that we've got a working build file, let's take a closer look at it's contents:
- Project
The project is the root element of the build file, it contains one or more targets. The default attribute is required and specifies the default build target (in this case: "hello").
- Target
A target represents a project milestone in ant, it contains zero or more tasks. The name attribute is required and specifes the name of the target (in this case: "hello"). Users may specify which target that would like to achieve via the command line (see below).
- Task (echo in this case)
Tasks are the smallest units of work in ant. Tasks may operate on many files, but the same operation will be applied to each file.
The echo task's message attribute specifies the text that is generated by this task.
</LI>
</LI>
Next, let's create another build file and examine some common
command line options in ant. Copy the following lines into a file named "echo.xml" (the new lines are shown in bold).
<project default="hello">
<target name="hello">
<echo message="Hello, World"/>
</target>
<target name="goodbye">
<echo message="Goodbye, Cruel World"/>
</target></project>
Execute ant using:
- -f echo.xml to specify "echo.xml" as the build file
- goodbye to specify "goodbye" as the target rather than the default
$ ant -f echo.xml goodbye
Buildfile: echo.xml
goodbye:
[echo] Goodbye, Cruel World
BUILD SUCCESSFUL
Total time: 2 seconds
Finally, let's take a look at the target depends attribute. Edit "echo.xml" and add the target "all" as shown below:
<project default="hello">
<target name="hello">
<echo message="Hello, World"/>
</target>
<target name="goodbye">
<echo message="Goodbye, Cruel World"/>
</target>
<target name="all" depends="hello,goodbye" /></project>
The target
depends attribute specifies targets that should be achieved prior to executing the current target. Ant will attempt to execute depends targets left to right, but this may be altered by their respective depends targets. In this case "hello" and "goodbye" have no dependencies, so they will execute in that order.
$ ant -f echo.xml all
Buildfile: echo.xml
hello:
[echo] Hello, World
goodbye:
[echo] Goodbye, Cruel World
all:
BUILD SUCCESSFUL
Total time: 2 seconds