콘텐츠로 이동

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

기본 명령어

명령어설명
ant -versionAnt 버전, Java 버전, 운영 체제 정보 표시
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-debug의 약어
ant -quiet test최소한의 출력, 오류만 표시
ant -q build조용한의 약어
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 -findbuild.xml을 위해 상위 디렉토리 검색
ant -s-f
ant -keep-going test실패 후에도 독립적인 대상 실행 계속하기
ant -k test계속-가기의 약어
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>

사용 사례: 웹 애플리케이션용 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"/>