1. 程式人生 > >ant專案構建(打jar包小案例)

ant專案構建(打jar包小案例)

ant介紹不說了,在此直接使用ant為專案打一個jar包,在開始之前,先說下ant環境的搭建

ant環境準備:

首先安裝好JDK,配置好JAVA_HOME與PATH;

其次下載ant包,直接解壓,配置ANT_HOME與PATH環境變數;

最後測試ant環境是否搭建成功:cmd下輸入ant -version,出現ant版本資訊說明ant環境搭建成功

利用ant打jar包

先編寫build.xml構建檔案,如下

<?xml version="1.0"?>

<project name="HelloWorld" default="pack"> 

	<property name="src.dir" value="src" />  
	<property name="report.dir" value="report" />
	<property name="classes.dir" value="classes" />
	<property name="lib.dir" value="lib" /> 
	<property name="dist.dir" value="dist" /> 	

	<!-- 定義classpath -->
	<path id="master-classpath"> 
		<fileset file="${lib.dir}/*.jar" />  
		<pathelement path="${classes.dir}"/>  
	</path>

	<!-- 初始化任務 -->
	<target name="init">
	</target>

	<!-- 編譯 -->	
	<target name="compile" depends="init" description="compile the source files"> 
		<mkdir dir="${classes.dir}"/> 
		<javac srcdir="${src.dir}" destdir="${classes.dir}" includeAntRuntime="false" target="1.7">  
			<classpath refid="master-classpath"/>  
		</javac> 
	</target>

	<!-- 測試 -->	
	<target name="test" depends="compile" description="run junit test">	 
		<mkdir dir="${report.dir}"/> 
		<junit printsummary="on"  
		haltonfailure="false" 
		failureproperty="tests.failed"	  
		showoutput="true">	  
			<classpath refid="master-classpath" />	 
			<formatter type="plain"/> 
			<batchtest todir="${report.dir}"> 
				<fileset dir="${classes.dir}">
					<include name="**/*Test.*"/> 
				</fileset>	  
			</batchtest>  
		</junit> 
		<fail if="tests.failed">
			****   One or more tests failed!   Check the output ...   ****
		</fail> 
	</target>

	<!-- 打包成jar -->	  
	<target name="pack" depends="test" description="make .jar file"> 
		<mkdir dir="${dist.dir}" /> 
		<jar destfile="${dist.dir}/hello.jar" basedir="${classes.dir}">  
			<exclude name="**/*Test.*" /> 
			<exclude name="**/Test*.*" />	 
		</jar>
	</target>  
	
</project>

準備一個專案HelloWorld,目前不會上傳,有需要的可以加群583890954和我要,或者自己寫一個都可以

將build.xml放到HelloWorld專案根下,然後cmd下輸入ant回車就可以了,顯示結果:

D:\test\HelloWorld>ant
Buildfile: D:\test\HelloWorld\build.xml

init:

compile:
    [mkdir] Created dir: D:\test\HelloWorld\classes
    [javac] Compiling 2 source files to D:\test\HelloWorld\classes

test:
    [mkdir] Created dir: D:\test\HelloWorld\report
    [junit] Running com.x.SayHelloTest
    [junit] ketty hello!
    [junit] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.01 sec

pack:
    [mkdir] Created dir: D:\test\HelloWorld\dist
      [jar] Building jar: D:\test\HelloWorld\dist\hello.jar

BUILD SUCCESSFUL
Total time: 0 seconds

D:\test\HelloWorld>