前面已经介绍了怎样通过Ant来编译和运行一个Java程序,下面我们接着来学习如何通过Ant来发布一个这样的工程。文件结构如图所示,先建立相应的目录结构,我们这里继续使用前面的HelloAnt类。
发布后的目录结构如下:
hello-ant/src : 用来存放java源文件。
hello-ant/docs : 项目用到的一些资源文件。
hello-ant/lib:项目用到的第3方jar包和自己的jar包,这些jar包最后要发布到hello-ant/e/deploy/lib下。
hello-ant/build:由Ant动态创建,存放编译后的classes文件。
hello-ant/deploy:工程对外发布的目录,由ant动态创建。
build.xml:
- <?xml version="1.0" encoding="GB2312"?>
- <project default="deploy" basedir=".">
- <!-- 定义全局变量 -->
- <property name="root" value="." />
- <property name="build.classes" value="${root}/build/classes" />
- <property name="app.name" value="hello-ant" />
- <property name="app.jar" value="${app.name}.jar" />
- <!-- 初始化 构建相应目录 -->
- <target name="clearup" >
- <delete dir="${root}/deploy" />
- <mkdir dir="${root}/deploy/bin" />
- <mkdir dir="${root}/deploy/docs" />
- <mkdir dir="${root}/deploy/lib" />
- </target>
- <!-- 编译 -->
- <target name="compile" >
- <delete dir="${root}/build" />
- <mkdir dir="${root}/build/classes" />
- <javac srcdir="src/hello/ant" destdir="${root}/build/classes" />
- </target>
- <!-- 打包build/classes/下的所有class 文件到 hello-ant.jar 中-->
- <target name="jar" depends="compile">
- <jar basedir="${build.classes}" jarfile="${root}/lib/${app.jar}" />
- </target>
- <!-- 发布 -->
- <target name="deploy" depends="clearup, jar">
- <copy todir="${root}/deploy/docs">
- <fileset dir="${root}/docs">
- <include name="*.txt" />
- <include name="*.jsp" />
- <include name="*.jpg" />
- </fileset>
- </copy>
- <copy file="${root}/lib/${app.jar}" todir="${root}/deploy/lib" />
- </target>
- </project>
在DOS下执行
D:/>cd hello-ant
D:/hello-ant> ant -file build.xml
Buildfile: build.xml
clearup:
[mkdir] Created dir: K:/hello-ant/deploy/bin
[mkdir] Created dir: K:/hello-ant/deploy/docs
[mkdir] Created dir: K:/hello-ant/deploy/lib
[delete] Deleting directory K:/hello-ant/build
[mkdir] Created dir: K:/hello-ant/build/classes
compile:
[javac] Compiling 1 source file to K:/hello-ant/build/classes
jar:
[jar] Building jar: K:/hello-ant/lib/hello-ant.jar
deploy:
[copy] Copying 3 files to K:/hello-ant/deploy/docs
[copy] Copying 1 file to K:/hello-ant/deploy/lib
BUILD SUCCESSFUL
Total time: 1 second
这样工程就发布完成了。
target的depends属性表示这个target在执行时所要依靠的其他target。如果当前target需要依靠多个其他的target则在depends属性中用“,”间隔。这样ant会在执行此target的时候按照从左到右的顺序优先执行depends属性中指定的target。