実行可能なjarファイルの作成方法

現在のプロジェクトで実行可能なjarファイルを作成する必要があったので調べた結果をメモ。Maven2を利用。

実行可能なjarファイルを作成する場合、maven-assembly-pluginを利用する必要あり。
http://maven.apache.org/plugins/maven-assembly-plugin/

以下、pom.xmlを抜粋。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>sample</artifactId>
  <packaging>jar</packaging>
  <name>sample</name>
  <version>1.0.0</version>
  <dependencies>
    <dependency>
        :
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>com.example.SampleMain</mainClass>
            </manifest>
          </archive>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>attached</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
  • descriptorRefs要素でどんな形式のアセンブリを作成するか指定する。
  • mainClass要素で実行時に呼ばれるMainクラスを指定する。
  • executions要素でpackageフェーズが呼ばれた時に、同時にassemblyも呼ばれるように指定する。