Filed under: Java, Maven, — Tags: Executable jar, maven-assembly-plugin — Thomas Sundberg — 2011-03-05
Creating an executable jar from Maven is not really hard.
This example will show you how you can include stuff in a jar and make it executable while not including stuff that is needed only during the build.
The job is done in the plugin maven-assembly-plugin that will include all resources that
is available in the runtime classpath generated by Maven.
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>se.sigma.educational</groupId>
<artifactId>executable-jar</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Executable jar example</name>
<description>An example of an executable jar that includes one dependency and doesn't include another dependency
</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>executable-example</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>package-jar-with-dependencies</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>se.sigma.educational.Main</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
The depenency commons-math will be included in the final distribution. The dependency
junit will not be included, it's scope is set to test.
The main method that will be executed is implemented in se.sigma.educational.Main
To run it, execute java -jar executable-example.jar