コンテンツにスキップ

Apache Ant チートシート

Apache Ant チートシート

インストール

プラットフォームコマンド
Ubuntu/Debiansudo apt update && sudo apt install ant
RHEL/CentOS/Fedorasudo yum install ant or sudo dnf install ant
Arch Linuxsudo pacman -S apache-ant
macOS (Homebrew)brew install ant
Windows (Chocolatey)choco install ant
Manual (All Platforms)Download from apache.org, extract, set ANT_HOME and add bin/ to PATH
前提条件: Java JDK 8+ が必要。設定JAVA_HOME環境変数。

基本コマンド

コマンド説明
ant -versionAnt のバージョン、Java のバージョン、OS 情報を表示
antbuild.xmlで指定されたデフォルトターゲットを実行
ant compilebuild.xml から “compile” ターゲットを実行する
ant clean”clean”ターゲットを実行(通常はビルド成果物を削除)
ant -projecthelp利用可能なターゲットとその説明をすべて一覧表示
ant -p-projecthelpの短縮形
ant -f custom-build.xmlbuild.xml の代わりに別のビルドファイルを使用する
ant -buildfile mybuild.xml compileビルドファイルとターゲットを指定して実行
ant -verbose compile詳細な実行情報を表示
ant -v test-v
ant -debug packageトラブルシューティングのための最大詳細度
ant -d deploy-dbg
ant -quiet testエラーのみを表示する最小限の出力
ant -q buildq
ant -logfile build.log compile出力を指定されたログファイルにリダイレクトする
ant -l output.log test-log

高度な使用法

コマンド説明
ant -Denv=production deployコマンドラインでプロパティ値を設定する
ant -Dversion=1.2.3 -Dbuild.number=456 package複数のプロパティを設定
ant -propertyfile custom.properties build外部ファイルからプロパティを読み込む
ant -findビルドファイル build.xml を親ディレクトリから検索する
ant -s-f
ant -keep-going test失敗後も独立したターゲットの実行を継続する
ant -k test-kg
ant -diagnosticsシステム情報と設定の詳細を表示
ant -listener org.apache.tools.ant.listener.Log4jListener compileカスタムビルドイベントリスナーを追加
ant -logger org.apache.tools.ant.NoBannerLogger compileカスタムロガー実装を使用
ant -inputhandler org.apache.tools.ant.input.SecureInputHandler deployセキュアな入力のためにカスタム入力ハンドラを使用する
ant -noclasspath compileCLASSPATHの環境変数を無視する
ant -autoproxy downloadJavaプロキシ設定を自動的に構成する
ant -lib /path/to/jars compileAnt のクラスパスに JAR のディレクトリを追加
ant -Dant.executor.class=org.apache.tools.ant.helper.ParallelExecutor build並列タスク実行を有効にする
ant compile test packageシーケンス内で複数のターゲットを実行
ant -Dskip.tests=true packageプロパティに基づいて条件付きでタスクをスキップする

設定

基本的な build.xml の構造

<?xml version="1.0" encoding="UTF-8"?>
<project name="MyProject" default="build" basedir=".">
    
    <!-- Properties -->
    <property name="src.dir" value="src"/>
    <property name="build.dir" value="build"/>
    <property name="dist.dir" value="dist"/>
    <property name="lib.dir" value="lib"/>
    
    <!-- Classpath -->
    <path id="classpath">
        <fileset dir="${lib.dir}">
            <include name="**/*.jar"/>
        </fileset>
    </path>
    
    <!-- Clean target -->
    <target name="clean" description="Remove build artifacts">
        <delete dir="${build.dir}"/>
        <delete dir="${dist.dir}"/>
    </target>
    
    <!-- Init target -->
    <target name="init" depends="clean">
        <mkdir dir="${build.dir}"/>
        <mkdir dir="${dist.dir}"/>
    </target>
    
    <!-- Compile target -->
    <target name="compile" depends="init" description="Compile source code">
        <javac srcdir="${src.dir}" 
               destdir="${build.dir}"
               classpathref="classpath"
               includeantruntime="false"
               debug="true"
               source="11"
               target="11"/>
    </target>
    
    <!-- Build target -->
    <target name="build" depends="compile" description="Build JAR file">
        <jar destfile="${dist.dir}/${ant.project.name}.jar" 
             basedir="${build.dir}">
            <manifest>
                <attribute name="Main-Class" value="com.example.Main"/>
            </manifest>
        </jar>
    </target>
    
</project>

build.properties ファイル

# Project configuration
project.name=MyApplication
project.version=1.0.0

# Directory structure
src.dir=src/main/java
test.dir=src/test/java
resources.dir=src/main/resources
build.dir=target/classes
dist.dir=dist

# Compiler settings
java.source.version=11
java.target.version=11
javac.debug=true
javac.deprecation=true

# Dependencies
lib.dir=lib

build.xml でのプロパティの読み込み

<property file="build.properties"/>
<property file="build-${env}.properties"/>
<property environment="env"/>

一般的なファイルセットとパターン

<!-- Include all Java files -->
<fileset dir="${src.dir}" includes="**/*.java"/>

<!-- Exclude test files -->
<fileset dir="${src.dir}">
    <include name="**/*.java"/>
    <exclude name="**/*Test.java"/>
</fileset>

<!-- Pattern sets for reuse -->
<patternset id="source.patterns">
    <include name="**/*.java"/>
    <include name="**/*.properties"/>
    <exclude name="**/*Test.java"/>
</patternset>

一般的なユースケース

ユースケース: 完全な Java アプリケーションのビルド

# Clean previous builds
ant clean

# Compile, test, and package in one command
ant compile test package

# Build with specific environment properties
ant -Denv=production -propertyfile prod.properties package

# Create distribution with documentation
ant clean compile test package javadoc dist

build.xml のターゲット:

<target name="test" depends="compile">
    <junit printsummary="yes" haltonfailure="yes">
        <classpath>
            <path refid="classpath"/>
            <pathelement location="${build.dir}"/>
        </classpath>
        <batchtest fork="yes">
            <fileset dir="${test.dir}">
                <include name="**/*Test.java"/>
            </fileset>
        </batchtest>
    </junit>
</target>

<target name="javadoc">
    <javadoc sourcepath="${src.dir}" 
             destdir="${dist.dir}/docs"
             packagenames="com.example.*"/>
</target>

ユースケース: Web アプリケーション用の WAR ファイル作成

# Build and package web application
ant clean compile war

# Deploy to application server
ant -Dserver.path=/opt/tomcat/webapps deploy

build.xml の設定:

<target name="war" depends="compile">
    <war destfile="${dist.dir}/${project.name}.war" 
         webxml="web/WEB-INF/web.xml">
        <classes dir="${build.dir}"/>
        <lib dir="${lib.dir}"/>
        <fileset dir="web">
            <include name="**/*.jsp"/>
            <include name="**/*.html"/>
            <include name="**/*.css"/>
            <include name="**/*.js"/>
        </fileset>
    </war>
</target>

<target name="deploy" depends="war">
    <copy file="${dist.dir}/${project.name}.war" 
          todir="${server.path}"/>
</target>

ユースケース: マルチモジュールプロジェクトのビルド

# Build all modules in parallel
ant -Dant.executor.class=org.apache.tools.ant.helper.ParallelExecutor build-all

# Build specific module
ant -Dmodule=core build-module

# Build and run integration tests
ant build-all integration-test

サブプロジェクト付きの build.xml:

<target name="build-all">
    <subant target="build">
        <fileset dir="." includes="*/build.xml"/>
    </subant>
</target>

<target name="build-module">
    <ant dir="${module}" target="build" inheritAll="false"/>
</target>

ユースケース: プロパティチェックによる条件付きビルド

# Skip tests during build
ant -Dskip.tests=true package

# Build only if sources changed
ant -Dincremental=true compile

# Production build with optimizations
ant -Doptimize=true -Ddebug=false production-build

条件付きの build.xml:

<target name="compile">
    <javac srcdir="${src.dir}" 
           destdir="${build.dir}"
           debug="${debug}"
           optimize="${optimize}">
        <classpath refid="classpath"/>
    </javac>
</target>

<target name="test" unless="skip.tests">
    <junit printsummary="yes">
        <classpath>
            <path refid="classpath"/>
            <pathelement location="${build.dir}"/>
        </classpath>
        <batchtest>
            <fileset dir="${test.dir}" includes="**/*Test.java"/>
        </batchtest>
    </junit>
</target>

<target name="package" depends="compile,test">
    <jar destfile="${dist.dir}/${ant.project.name}.jar" 
         basedir="${build.dir}"/>
</target>

ユースケース: データベース移行とデプロイメント

# Run database migrations
ant -propertyfile db-config.properties db-migrate

# Deploy application with database updates
ant -Denv=staging db-migrate deploy

# Rollback database changes
ant -Dversion=1.2.0 db-rollback

SQL タスク付きの build.xml:

<target name="db-migrate">
    <sql driver="${db.driver}"
         url="${db.url}"
         userid="${db.user}"
         password="${db.password}"
         src="migrations/migrate-${version}.sql"
         print="yes"
         output="migration.log"/>
</target>

<target name="db-rollback">
    <sql driver="${db.driver}"
         url="${db.url}"
         userid="${db.user}"
         password="${db.password}"
         src="migrations/rollback-${version}.sql"/>
</target>

ベストプラクティス

  • 設定にプロパティファイルを使用: 環境固有の設定をビルドロジックから分離。<property file="build.properties"/> to keep build.xml clean and reusable.

  • Define meaningful target descriptions: Add 説明 attributes to public targets for better ant -projecthelp output. This serves as built-in documentation for your build process.

  • Leverage target dependencies: Use depends attribute to establish build order and avoid redundant task execution. Ant automatically handles dependency resolution.

  • Set includeantruntime="false" in javac tasks: Prevents Ant runtime libraries from polluting your application classpath, avoiding potential conflicts and reducing JAR size.

  • Use filesets and pattern sets for flexibility: Define reusable file patterns with <patternset> and reference them in multiple targets. This makes maintenance easier and reduces duplication.

  • Implement incremental builds: Use <uptodate> conditions to skip compilation when source files haven’t changed, significantly speeding up development builds.

  • Version control your build files: Include build.xml, property files, and custom tasks in version control. Exclude generated directories like build/ and dist/ using .gitignore.

  • Use macros for repeated task sequences: Define <macrodef> elements for common operations performed across multiple modules or targets, promoting DRY principles.

  • Separate concerns with imported build files: Split large build files into logical components (common-build.xml, `test-build.xml を取り込み、保守性を向上させます。

  • 複雑なロジックをコメントで説明する: XMLコメントを使用して、共有またはレガシープロジェクトの非自明なビルドロジック、プロパティの使用、依存関係を説明します。

トラブルシューティング

問題ソリューション
BUILD FAILED: build.xml does not existRun ant -find to search parent directories, or specify file with ant -f path/to/build.xml
Unable to locate tools.jarSet JAVA_HOME to JDK (not JRE) directory. Verify with echo $JAVA_HOME and ensure it points to JDK installation
ClassNotFoundException for custom tasksAdd JAR to Ant’s classpath using -lib option: ant -lib /path/to/jars compile or use <taskdef> with correct classpath
Compilation fails with encoding errorsAdd encoding="UTF-8" attribute to <javac> task: <javac srcdir="${src.dir}" encoding="UTF-8"/>
Out of memory during buildIncrease heap size: export ANT_OPTS="-Xmx1024m -Xms512m" (Linux/Mac) or set ANT_OPTS=-Xmx1024m (Windows)
Target not found errorVerify target name with ant -projecthelp. Check for typos and ensure target is defined in active build file
Circular dependency detectedReview depends attributes in targets. Ant cannot resolve circular references - redesign target dependencies
Permission denied when writing filesディレクトリのパーミッションを確認し、Antに書き込みアクセス権があることを確認してください。適切なユーザー権限で実行するか、ディレクトリの所有権を調整してください。
fork="true" required but task failsSome tasks (junit, java) require forking. Ensure fork="true" is set and JAVA_HOME points to valid JDK
Properties not being overriddenProperties are immutable in Ant - first definition wins. Set properties via command line (-D) before build file loads them
Slow builds with large filesetsUse <uptodate> conditions for incremental builds. Enable parallel execution with -Dant.executor.class=org.apache.tools.ant.helper.ParallelExecutor
JAR file manifest not correctUse <manifest> element within <jar> task to specify Main-Class and other attributes explicitly

Antタスク共通リファレンス

タスク説明
<javac>Javaソースファイルをコンパイルする<javac srcdir="src" destdir="build" includeantruntime="false"/>
<jar>JARアーカイブを作成<jar destfile="dist/app.jar" basedir="build"/>
<war>WAR アーカイブを作成<war destfile="dist/app.war" webxml="web/WEB-INF/web.xml"/>
<copy>ファイルまたはディレクトリをコピーする<copy todir="backup"><fileset dir="src"/></copy>
<delete>ファイルまたはディレクトリを削除<delete dir="build"/>
<mkdir>ディレクトリを作成<mkdir dir="dist"/>
<echo>メッセージを印刷する<echo message="Building version ${version}"/>
<exec>システムコマンドを実行<exec executable="git" args="rev-parse HEAD"/>
<junit>JUnitテストを実行する<junit printsummary="yes" fork="yes"/>
<zip>ZIPアーカイブを作成<zip destfile="dist/src.zip" basedir="src"/>
<sql>SQLステートメントを実行する<sql driver="${db.driver}" url="${db.url}" src="schema.sql"/>