Automatically build and deploy "Go" for Java projects with Ant

Source: Internet
Author: User
Tags echo message

Original address: http://tech.it168.com/j/2007-11-09/200711091344781.shtml
Please do not reprint this article!

Ant is a cross-platform component tool under the Apache Foundation that enables the automatic building and deployment of projects. In this article, it's important to familiarize the reader with how to apply ant to a Java project, allowing it to simplify build and deployment operations.

A. Installation and configuration

: http://ant.apache.org/, downloaded in this article is version 1.7.0. Unzip to a directory (for example, E: "apache-ant-1.7.0") and you can use it.

Add the System environment variable: Ant_home, which points to the root directory of ANT decompression, where E: "apache-ant-1.7.0.

After installation and configuration, the reader can test if Ant is available, first into the Ant bin directory, Run command ant–version, and if the installation and configuration are successful, the ant version information is displayed as shown in:

As you can see, when the reader runs Ant's command, it needs to go into the ant's Bin directory, how can the system automatically find ant? The reader is required to add the ant Bin directory to the System environment variable path. After the setup is complete, we can enter Ant's command in any directory (for example, C: "Documents and Settings" Amigoxie directory) to get the result of running the command.

two. key elements of Ant

Ant's artifact file is XML-based and the default name is Build.xml. To get a clearer idea of ant, write a simple ant program here that shows Ant's functionality and gives the reader a rudimentary understanding of ant. First, a build.xml file is created under the E disk, which reads as follows:

<?xml version= "1.0"?>
<project name= "HelloWorld" >
<target name= "SayHelloWorld" >
<echo message= "Hello,amigo"/>
</target>
</project>

Readers can enter the E-drive and then run Ant SayHelloWorld to see the following running results:

Where SayHelloWorld is the name of the task that needs to be performed. If the file name is not build.xml, and the reader runs the same command when Hello.xml, the command window will appear with the following error:

Buildfile:build.xml does not exist!

Build failed

As you can see by the above command's error, the ant command looks for the Build.xml file by default. If the file name is Hello.xml, the reader will also need to change the command slightly, instead: Ant–f hello.xml sayhelloworld, ant–buildfile hello.xml SayHelloWorld or Ant–file Hello.xml SayHelloWorld.

Let's start by explaining the focus of this section to the reader: The key elements of Ant are project, target, property, and task.

1. Project elements

The project element is the root element of the ant artifact file, and the ant component file should contain at least one project element, or an error will occur. Under each project element, you can include multiple target elements. Next, show the reader the properties of the project element.

1) name Properties

Used to specify the name of the project element.

2) default Properties

Specifies the name of the target to execute when project is executed by default.

3) Basedir Properties

Used to specify the location of the base path. When this property is not specified, use the attached directory of the ant's artifact file as the base directory.

Here's a simple example to show the use of the elements of Project. Modify e: "Build.xml file, the modified content is as follows:

<?xml version= "1.0"?>
<project name= "Projectstudy" default= "Saybasedir" basedir= "E:" apache-ant-1.7.0 ">
<target name= "Saybasedir" >
<echo message= "The base dir is: ${basedir}"/>
</target>
</project>

From the above, we can see that the value of the default property is defined here as Saybasedir, that is, when the ant command is run, if the target executed by default is not specified, Saybasedir of the target is executed, and the value of the Basedir property is defined as E : "apache-ant-1.7.0, after entering the e-disk, run the ant command to see the results of the run, as shown in:

Because the value of Basedir is set, the value of the Basedir property becomes the value that the reader sets. The reader can remove the Basedir attribute of the project element and run ant to see the result of the run, at which point the value of Basedir becomes e: ", which is the parent directory of the ant artifact file.

Sometimes the reader may have the need to get all the target names under a project, and the reader can do so by adding-proecthelp to the ant command. For example, for the above example we run Ant–projecthelp and the output is as follows:

Buildfile:build.xml

Main Targets:

Other targets:

Saybasedir

Default Target:saybasedir

2. target element

It is the basic execution unit of ant, which can contain one or more specific tasks. Multiple target can exist interdependencies. It has the following properties:

1) name Properties

Specifies the name of the target element, which is unique within a project element. We can specify a target by specifying the name of the target element.

2) depends Properties

Used to describe a dependency between target and, if there is a dependency on more than one target, the "," interval is required. Ant executes each target sequentially, in the order in which the target appears in the Depends property. The target to be relied upon will be executed first.

3) if Properties

Used to verify that the specified property exists, and if it does not exist, the target will not be executed.

4) unless Properties

The function of this property is the opposite of the function of the If property, and it is also used to verify that the specified property exists and, if it does not exist, the target will be executed.

5) Description Properties

This property is a short description and description of the target feature.

Let's take a look at an example of how each attribute is used in combination. Modify e: "Build.xml file, the modified content is as follows:

<?xml version= "1.0"?>
<project name= "Targetstudy" >
<target name= "Targeta" if= "Ant.java.version" >
<echo message= "Java Version: ${ant.java.version}"/>
</target>
<target name= "Targetb" depends= "Targeta" unless= "Amigo" >
<description>
A depend example!
</description>
<echo message= "The base dir is: ${basedir}"/>
</target>
</project>

Run Ant Targetb after entering the E-drive to see the results as shown:

After analyzing the results, we can see that we are running target named Targetb, because the target relies on Targeta, so Targeta will be executed first, and because the system has a Java environment installed, So the Ant.java.version attribute exists, executes the Targeta this target, the output information: [echo] Java Version:1.5,targeta after execution, then execute TARGETB, because Amigo does not exist, The unless attribute is entered at Target when it does not exist, so TARGETB can execute and output information: the base dir is:e: ".

3. Property elements

This element can be thought of as a parameter or an argument, and the properties of project can be set by the property element or outside of ant. To introduce a file externally, such as a build.properties file, you can introduce it by introducing the following: <property file= "Build.properties"/>

Property elements can be used as attribute values for a task. In a task, this is done by placing the property name between "${" and "}" and placing it in the position of the task property value.

Ant provides some built-in properties that give a list of system properties that are consistent with the properties of the System.getpropertis () method in the Java documentation, which can be referenced by the Sun Web site's description.

At the same time, Ant also provides some of its own built-in properties, as follows:

The absolute path to the Basedir:project base directory, which is explained in detail when explaining project elements, and is no longer described;

Ant.file:buildfile absolute path, as in the above example, the value of Ant.file is e: "Build.xml;

The ant.version:Ant version, in this article, has a value of 1.7.0;

Ant.project.name: The name of project that is currently specified, that is, the value of project's Name property as mentioned earlier;

The version of the JDK detected by ANT.JAVA.VERSION:ANT, as shown in the results of the previous example run, is 1.5.

Let the reader see a simple example of the use of a property element. Modify e: "Build.xml file with the following content:

<?xml version= "1.0"?>
<project name= "Propertystudy" default= "Example" >
<property name= "name" value= "Amigo"/>
<property name= "age" value= "/>"
<target name= "Example" >
<echo message= "Name: ${name}, Age: ${age}"/>
</target>
</project>

The result of this example is as follows:

As you can see from this reader, there are two statements:

<property name= "name" value= "Amigo"/>

<property name= "age" value= "/>"

We set up two properties named name and age, and after these two properties are set, the reader can obtain the values of these two properties by ${name} and ${age}, respectively.

three. Ant 's Common tasks

Each task in the Ant tool encapsulates the specific functionality to be performed and is the basic execution unit of the Ant tool. In this section, we mainly guide the reader to look at Ant's Common tasks and their use examples.

1. copy task

This task is primarily used for copying files and directories. Examples are as follows:

Eg1. Copying a single file: <copy file= "file.txt" tofile= "Copy.txt"/>

Eg2. Copying a file directory:

<copy todir= ". /newdir/dest_dir ">

<fileset dir= "Src_dir"/>

</copy>

Eg3. Copy the file to a different directory:

<copy file= "file.txt" todir= ". /other/dir "/>

2. Delete task

To delete a file or directory, see the following example:

Eg1. Delete a file: <delete file= "Photo/amigo.jpg"/>

Eg2. Delete a directory: <delete dir= "Photo"/>

Eg3. Delete all backup directories or empty directories:

<delete includeemptydirs= "true" >

<fileset dir= "." includes= "**/*.bak"/>

</delete>

3. mkdir Tasks

Create a directory. Eg:<mkdir dir= "Build"/>

4. Move task

To move a file or directory, for example:

Eg1. Move individual files: <move file= "FromFile" tofile= "ToFile"/>

Eg2. Move a single file to another directory: <move file= "FromFile" todir= "Movedir"/>

Eg3. To move a directory to another directory:

<move todir= "Newdir" >

<fileset dir= "Olddir"/>

</move>

5. echo task

The purpose of this task is to output information based on the level of the log or monitor. It includes the message, file, append, and level four properties, for example:

<echo message= "Hello,amigo" file= "Logs/system.log" append= "true" >

Four. Build and deploy Java engineering with Ant

Ant can instead use commands such as Javac, Java, and jars to perform Java operations, making it easy to build and deploy Java engineering. Let's look at a few points of knowledge.

1. use ant 's javac task to compile Java programs

Ant's Javac task is used to implement the functionality of compiling Java programs. Let's look at a simple example:

First we set up a Java project called Antstudy, build the SRC directory as the source code directory, in the SRC directory to build helloworld.java this kind of file. The contents of this type of file are as follows:

public class HelloWorld{
public static void Main (string[] args) {
System.out.println ("Hello,amigo");
}
}

At the same time, in the root directory of the Antstudy project to build the Build.xml file, in this file to compile the src directory of java files, and the compiled class file into the Build/classes directory, before compiling, you need to clear the classes directory, The contents of the file are as follows:

<?xml version= "1.0"?>
<project name= "Javactest" default= "Compile" basedir= "." >
<target name= "clean" >
<delete dir= "Build"/>
</target>

<target name= "Compile" depends= "clean" >
<mkdir dir= "Build/classes"/>
<javac srcdir= "src" destdir= "build/classes"/>
</target>
</project>

Run the Build.xml file to see the new build/classes directory in the project and generate the compiled Helloworld.class file in that directory.

2. running Java programs using Ant 's Java task

The ability to run Java programs can be implemented in Ant using Java tasks. The following changes are made in the 1 example below, and the contents of the modified Build.xml file are as follows:

<?xml version= "1.0"?>
<project name= "javatest" default= "Jar" basedir= "." >
<target name= "clean" >
<delete dir= "Build"/>
</target>

<target name= "Compile" depends= "clean" >
<mkdir dir= "Build/classes"/>
<javac srcdir= "src" destdir= "build/classes"/>
</target>

<target name= "Run" depends= "compile" >
<java classname= "HelloWorld" >
<classpath>
<pathelement path= "Build/classes"/>
</classpath>
</java>
</target>
</project>

Running the Build.xml file, you can see the output of the HelloWorld Main method in the console.

3. Build the jar file using the ant's Jar task

The reader can build the jar package on the basis of the example above, and add the following target under the run target:

<target name= "Jar" depends= "Run" >
<jar destfile= "Helloworld.jar" basedir= "build/classes" >
<manifest>
<attribute name= "Main-class" value= "HelloWorld"/>
</manifest>
</jar>
</target>

At this point, you set the default property of the Ant project to a jar, run the Build.xml file, and when you are finished, you can see that a jar package Helloworld.jar is generated under the project directory.

4. use Ant 's War task to package the java EE Web Project

Build a Java EE Web project with the directory structure as shown:

Where SRC is the source code directory, Webroot for each JSP storage directory, LIB for the project package directory. The Build.xml file was created under the Antwebproject project directory, which is the ant component file for the project. The reader can be placed in the SRC directory in the previous example of the development of the Helloworld.java file, and Webroot under the creation of index.jsp file, the content is very simple, is to output hello information, the code is as follows:

<%@ Page language= "java" contenttype= "text/html; charset= "UTF-8" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=iso-8859-1 ">
<title>ant Packaging Test </title>
<body>
Hello,ant
</body>

Next, write the Build.xml file, which reads as follows:

<?xml version= "1.0"?>
<project name= "Antwebproject" default= "war" basedir= "." >
<property name= "Classes" value= "build/classes"/>
<property name= "Build" value= "Build"/>
<property name= "Lib" value= "Webroot/web-inf/lib"/>
<!--Delete the build path--
<target name= "clean" >
<delete dir= "Build"/>
</target>

<!--build the build/classes path and compile the class file to the build/classes path--
<target name= "Compile" depends= "clean" >
<mkdir dir= "${classes}"/>

<javac srcdir= "src" destdir= "${classes}"/>
</target>

<!--War Pack--
<target name= "war" depends= "compile" >
<war destfile= "${build}/antwebproject.war" webxml= "Webroot/web-inf/web.xml" >
<!--copy Webroot under two folders in addition to Web-inf and Meta-inf--
<fileset dir= "WebRoot" includes= "**/*.jsp"/>

<!--Copy the jar package in the Lib directory--
<lib dir= "${lib}"/>
<!--copy the class file under Build/classes--
<classesdir= "${classes}"/>
</war>
</target>
</project>

The role of the target has been explained in the content and is not discussed here. After you run the build file and update the catalog, you can see that the Antwebproject.war file was generated under the build directory, and you can see its directory structure as follows:

--meta-inf

--manifest. Mf

--index.jsp

--web-inf

--lib

--log4j-1.2.9.jar

--classes

--helloworld.class

--web.xml

Readers can copy the war package to the Tomcat directory to see the results of the run.

Five. Summary

In this paper, I describe ant's installation and configuration, key elements and common tasks in detail from shallow to deep. The application of ant in our Java project is narrated by examples, and the knowledge of compiling, running Java program, and playing jar bag and war package are introduced, which leads the reader into the wonderful world of Ant. As you can see in this article, Ant is an easy-to-use and flexible way to build and deploy Java programs automatically, and is a great helper for our Java developers.

Automatically build and deploy "Go" for Java projects with Ant

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.