2011年11月8日 星期二

Apache Ant - Build WAR Files of Spring Web Service

By this post, we can build a WAR file to deploy our Spring web service. However, we can leverage Apache Ant pure Java build tool to build it.

First, we need to create a new directory lib/ and put all JARs in it. (all Spring framework JAR files and commons-logging JAR file). Then create build.xml in our project:

<?xml version="1.0" encoding="UTF-8"?>
    
<project name="EchoService" basedir="." default="war">

    <property name="src.dir"     value="src" />
    <property name="lib.dir"     value="lib" />
    <property name="build.dir"   value="build" />
    <property name="classes.dir" value="${build.dir}/classes" />
    <property name="dest.dir"    value="${build.dir}/release" />
    <property name="web.dir"     value="WebContent" />
    <property name="web.inf.dir" value="${web.dir}/WEB-INF" />
    <property name="web.lib.dir" value="${web.inf.dir}/lib" />    
        
    <path id="classpath">
        <fileset dir="${lib.dir}" />
    </path>
        
    <target name="clean">
        <delete dir="${build.dir}" />
        
        <delete includeemptydirs="true">
            <fileset dir="${web.lib.dir}" includes="**/*"/>
        </delete>

        <delete file="${web.inf.dir}/applicationContext.xml" />
    </target>
    
    <target name="init" depends="clean">
        <tstamp>
            <format property="TODAY_TS" pattern="yyyyMMdd.HHmm" locale="en,UK" />
        </tstamp>
    </target>
    
    <target name="compile" depends="init">
        <mkdir dir="${classes.dir}" />
        
        <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false" debug="true">
            <classpath refid="classpath" />
            <include name="**/*.java" />
        </javac>
    </target>

    <target name="war" depends="compile">
        <copy todir="${web.lib.dir}">
            <fileset dir="${lib.dir}" />
        </copy>

        <copy todir="${web.inf.dir}" flatten="true">
            <fileset dir="${src.dir}" includes="**/applicationContext.xml" />
        </copy>
    
        <war destfile="${dest.dir}/EchoService.war">
            <fileset dir="${web.dir}" />
            <lib dir="${web.lib.dir}" />
            <classes dir="${classes.dir}" />
        </war>
    </target>    
        
</project>

build.xml is quite self-explanatory:
  1. Delete duplicated files! Don't worry, we will copy these files again while building a WAR file.
  2. Compile all Java source files to classes for further building.
  3. Build a WAR file: Copy all JAR files and applicationContext.xml. Then indicate fileset, lib, classes properties for war task. Done.
After building, we should deploy the WAR file to check if the Spring web service (EchoService) is available. Enjoy!

(PS. If we add <lib dir="${web.lib.dir}" />, the size of the WAR file will be doubled.)

沒有留言:

張貼留言