このチュートリアルでは、Antビルドスクリプトを使用してJarファイルを作成し、プロジェクトの外部ライブラリ/依存関係を操作する方法を説明します。

使用される技術:

  1. Eclipse 4.2

  2. JDK 1.7

  3. アリ1.9.4

  4. Ant-Ivy 2.4

  5. ログバック1.1.2

  6. joda-time 2.5

__P.S以前のリンク://ant/ant-how-to-create-a-java-project/[Ant Javaプロジェクト]が再利用されます。

1.プロジェクトの構成


Figure 1.1:Eclipse IDE.

の最終プロジェクトディレクトリ構造


ant-external-libraries-final、width = 727、height = 525

2. Javaプロジェクトの外部ライブラリ

Eclipse IDEで、以前のJavaプロジェクトリンクを開きます。//ant/ant-how-to-create-a-java-project/[AntDateUtils]、

logback`と

joda-time`を使用するようにソースコードを更新します。

src/com/mkyong/core/utils/DateUtils.java

package com.mkyong.core.utils;

import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtils {

    private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);

    public static void main(String[]args) {

        logger.debug("[MAIN]Current Date : {}", getLocalCurrentDate());
        System.out.println(getLocalCurrentDate());

    }

    private static String getLocalCurrentDate() {

        LocalDate date = new LocalDate();
        return date.toString();

    }

}


logback.xml`を作成し、それをプロジェクトの

src`フォルダに置きます。図1.1を参照してください。

src/logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <layout class="ch.qos.logback.classic.PatternLayout">

        <Pattern>
            ANT + LogBack : %-5level %logger{36} - %msg%n
        </Pattern>

      </layout>
    </appender>

    <root level="debug">
      <appender-ref ref="STDOUT"/>
    </root>

</configuration>

3. Ivy – 外部ライブラリを取得する

Apache Ivyを使用して、プロジェクトの外部ライブラリ/依存関係を取得します。

3.1このファイル `ivy.xml`を作成します:

ivy.xml

<ivy-module version="2.0">
    <info organisation="org.apache" module="dateUtilsProject"/>
    <dependencies>
        <dependency org="joda-time" name="joda-time" rev="2.5" />
        <dependency org="org.slf4j" name="slf4j-api" rev="1.7.6"/>
        <dependency org="ch.qos.logback" name="logback-classic" rev="1.1.2"/>
    </dependencies>
</ivy-module>

3.2 `build.xml`を更新し、上部にivy名前空間を追加し、ivyモジュールをダウンロードするivyタスクと、外部ライブラリをダウンロードするようにIvyモジュールに依頼するタスクを解決します。

build.xml

<project xmlns:ivy="antlib:org.apache.ivy.ant"
    name="dateUtilsProject" default="main" basedir=".">

    <!-- ivy start -->
    <!-- ivy to get dependencies and copy to project lib folder automatically -->
    <target name="resolve" description="retrieve dependencies with ivy">
        <ivy:retrieve/>
    </target>

    <!-- install ivy -->
    <target name="ivy" description="Install ivy">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ivy.jar"
            src="https://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.4.0-rc1/ivy-2.4.0-rc1.jar"/>
    </target>
    <!-- ivy end -->

</project>

初めてMavenセンターリポジトリからローカルの `$ {user.home}/。ant/lib/ivy.jar`にivyモジュールをダウンロードしてください。

$ ant ivy

外部ライブラリをダウンロードするには、タスク “解決”を実行します。宣言されたライブラリは、プロジェクトの `lib`フォルダにダウンロードされます。

$ ant resolve

4. build.xml

更新された `build.xml`スクリプトを見直し、コメントを読んでください。

主なポイント:

  1. Apache Ivyでプロジェクトの外部ライブラリを管理し、アイビーを確認する

ネームスペースが一番上にあり、タスク「解決」があります。

  1. ソースコードをコンパイルするには、クラスパスを宣言する必要があります. レビュー

タスク「コンパイル」、および「クラスパスリファレンス」属性を含む。

  1. “jar”タスクでは、外部ライブラリのリスト全体を構築します

`manifest.mf`ファイルに入れてください。

  1. “jar”タスクでは、プロジェクトjarは “dist”フォルダにパッケージ化され、

外部ライブラリ全体が “lib”から “dist/lib”にコピーされます。

build.xml

<project xmlns:ivy="antlib:org.apache.ivy.ant"
       name="dateUtilsProject" default="main" basedir=".">
    <description>
        Create a Java Project (JAR) with Ant build script
    </description>

    <property name="projectName" value="DateUtils"/>
    <property name="src.dir" location="src"/>
    <property name="build.dir" location="bin"/>
    <property name="dist.dir" location="dist"/>
    <property name="dist.lib.dir" location="dist/lib"/>
    <property name="lib.dir" value="lib"/>
    <property name="main-class" value="com.mkyong.core.utils.DateUtils"/>

    <!-- ivy start -->
    <!-- ivy to get dependencies and copy to project lib folder automatically -->
    <target name="resolve" description="retrieve dependencies with ivy">
        <ivy:retrieve/>
    </target>

    <!-- install ivy -->
    <target name="ivy" description="Install ivy">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ivy.jar" src="https://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.4.0-rc1/ivy-2.4.0-rc1.jar"/>
    </target>
    <!-- ivy end -->

    <target name="init">
        <mkdir dir="${build.dir}"/>
    </target>

    <!-- external libraries classpath, we don't need sources and javadoc -->
    <path id="classpath">
        <fileset dir="${basedir}/">
            <include name="${lib.dir}/** .jar"/>
            <exclude name="${lib.dir}/** sources.jar"/>
            <exclude name="${lib.dir}/** javadoc.jar"/>
        </fileset>
    </path>

    <!-- To work with external libraries, need classpath to compile -->
    <target name="compile" depends="init" description="compile the source ">
        <javac includeantruntime="false" srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath"/>
    </target>

    <!-- constructs the external libraries classpath name -->
    <pathconvert property="classpath.name" pathsep=" ">
        <path refid="classpath"/>
        <mapper>
            <chainedmapper>
                <flattenmapper/>
                <globmapper from="** .jar" to="lib/** .jar"/>
            </chainedmapper>
        </mapper>
    </pathconvert>

    <target name="copy-dependencies">
        <copy todir="${dist.lib.dir}">
            <fileset dir="${lib.dir}" includes="** ** /** .jar" excludes="** ** /** sources.jar, ** ** /** javadoc.jar"/>
        </copy>
    </target>

    <!-- jar it, and declares the ext libraries in manifest.mf file -->
    <target name="jar" depends="compile, copy-dependencies" description="package, output to JAR">

        <echo message="classpath.name : ${classpath.name} "/>

        <mkdir dir="${dist.dir}"/>
        <mkdir dir="${dist.lib.dir}"/>

        <jar jarfile="${dist.dir}/${projectName}.jar" basedir="${build.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
                <attribute name="Class-Path" value="${classpath.name}"/>
            </manifest>
        </jar>
    </target>

    <target name="clean" description="clean up">
        <delete dir="${build.dir}"/>
        <delete dir="${dist.dir}"/>
    </target>

    <!-- Default, run this -->
    <target name="main" depends="clean, compile, jar"/>

</project>

5.テスト

AntビルドスクリプトでJavaプロジェクトをテストします。

5.1それを入れてください。

$ pwd/Users/mkyong/Documents/workspace/AntDateUtils

$ ant
Buildfile:/Users/mkyong/Documents/workspace/AntDateUtils/build.xml

clean:
  [delete]Deleting directory/Users/mkyong/Documents/workspace/AntDateUtils/bin
  [delete]Deleting directory/Users/mkyong/Documents/workspace/AntDateUtils/dist

init:
   [mkdir]Created dir:/Users/mkyong/Documents/workspace/AntDateUtils/bin

compile:
   [javac]Compiling 1 source file to/Users/mkyong/Documents/workspace/AntDateUtils/bin

copy-dependencies:
    [copy]Copying 12 files to/Users/mkyong/Documents/workspace/AntDateUtils/dist/lib

jar:
    [echo]classpath.name : ... lib/joda-time-2.5.jar lib/logback-classic-1.1.2.jar lib/logback-core-1.1.2.jar lib/mail-1.4.jar ...

     [jar]Building jar:/Users/mkyong/Documents/workspace/AntDateUtils/dist/DateUtils.jar

main:

BUILD SUCCESSFUL
Total time: 1 second

5.2生成されたjarファイルを検査します。

$ jar -tf dist/DateUtils.jar

META-INF/META-INF/MANIFEST.MF
com/com/mkyong/com/mkyong/core/com/mkyong/core/utils/com/mkyong/core/utils/DateUtils.class

META-INF/MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.4
Created-By: 1.7.0__05-b05 (Oracle Corporation)
Main-Class: com.mkyong.core.utils.DateUtils
Class-Path: lib/activation-1.1.jar lib/commons-compiler-2.6.1.jar lib/ geronimo-jms__1.1__spec-1.0.jar lib/groovy-all-2.0.7.jar lib/janino-2.6
 .1.jar lib/joda-convert-1.2.jar lib/joda-time-2.5.jar lib/logback-cla
 ssic-1.1.2.jar lib/logback-core-1.1.2.jar lib/mail-1.4.jar lib/servle
 t-api-2.5.jar lib/slf4j-api-1.7.6.jar

5.3 Jarファイルを実行します。

$ pwd/Users/mkyong/Documents/workspace/AntDateUtils

$ java -jar dist/DateUtils.jar

16:28:43.957[main]DEBUG com.mkyong.core.utils.DateUtils -[MAIN]Current Date : 2014-11-21
2014-11-21

5.4 Jarファイルを `logback.xml`で再実行します。

$ pwd/Users/mkyong/Documents/workspace/AntDateUtils

$ java -jar -Dlogback.configurationFile=src/logback.xml dist/DateUtils.jar

16:34:43,746 |-INFO in ch.qos.logback.classic.LoggerContext[default]- Found resource[src/logback.xml]at[file:/Users/mkyong/Documents/workspace/AntDateUtils/src/logback.xml]//...

ANT + LogBack : DEBUG com.mkyong.core.utils.DateUtils -[MAIN]Current Date : 2014-11-21
2014-11-21

ソースコードをダウンロードする

ダウンロードする –

AntDateUtils-External-Libraries.zip

(8 KB)

参考文献

アントハローワールドオフィシャルガイド]。 link://maven/how-to-create-a-jar-file-with-maven/[Jarを作成する方法

Mavenを持つファイル]。

Ant Jarタスク