ant工具是使用Java语言编写的,主要用于java项目的编译打包工具
ant就相当于java版的makefile。格式和语法非常简单,简单就意味着强大,但也意味着一切都要靠自己
和maven, gradle相比,ant几乎不提供内部支持,比如说要编译一个java项目,makefile需要你自己去调用javac。在ant中,你也差不多,得这样:
<target> <javac> ... </javac> </copy> </target>
而maven, gradle则不然,task和plugin都已经给你做好了,只需要build一下就完事。
从设计理念上,ant几乎就是makefile,需要自己把具体的执行指令封装到build.xml中
基本规范
ant的构建脚本是使用xml文件承载的,缺省命名为build.xml。进入其文件所在目录,可以在cmd中直接使用ant命令调用
build.xml的核心,是一个个的target。一个target对应着一条或者几条执行指令:
<project name="MyProject" default="dist" basedir="."> <description> simple example build file </description> <!-- set global properties for this build --> <property name="src" location="src"/> <property name="build" location="build"/> <property name="dist" location="dist"/> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/> </target> <target name="compile" depends="init" description="compile the source"> <!-- Compile the Java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="dist" depends="compile" description="generate the distribution"> <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file --> <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/> </target> <target name="clean" description="clean up"> <!-- Delete the ${build} and ${dist} directory trees --> <delete dir="${build}"/> <delete dir="${dist}"/> </target> </project>
- project 根标签。name属性表示项目名称,default属性表示默认执行命令,cmd命令行中使用ant和ant default属性值(本例是ant build) 两种方式等效。
- property 定义类标签。可以定义一些常量值,需要注意:定义后理论不能再修改(其实可以通过第三方库修改。
- target 执行标签。可以在cmd命令行中直接ant + target执行,比如以上脚本可以执行: ant clean 和 ant dist。target标签中有个depends属性,表示执行命令依赖。如果要执行dist命令,会自动先执行depends里面的命令。以上脚本执行 ant dist,会先执行 ant compile
Task
build.xml本身是xml文件,不可能像makefile那样直接写指令。ant中的指令是通过task来实现的。比如:
<mkdir dir="${dist}/lib"/> <javac srcdir="${src}" destdir="${build}"/>
<mkdir>, <javac>就是task。一眼就能看出,task就是xml格式的指令。ant提供了很多的task,但也可以自定义task
首先创建一个自定义task类:
package com.mydomain; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; public class MyVeryOwnTask extends Task { private String msg; // The method executing the task public void execute() throws BuildException { System.out.println(msg); } // The setter for the "message" attribute public void setMessage(String msg) { this.msg = msg; } }
在build.xml中引用该task:
<?xml version="1.0"?> <project name="OwnTaskExample" default="main" basedir="."> <taskdef name="mytask" classname="com.mydomain.MyVeryOwnTask"/> <target name="main"> <mytask message="Hello World! MyVeryOwnTask works!"/> </target> </project>
发表回复