The JAR artifact generated by Maven works well when used as a dependency in another project. However, it cannot be run as an executable without manually specifying the main class and explicitly specifying the dependencies that the project uses in the classpath.
What if we want to create an executable JAR for the project? This may be useful when the JAR needs to be tested or the project is a simple tool that should be invoked without additional effort.
project-with-executable-jar
):pom
file:<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.6</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.packt.cookbook.App</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build>
target
folder:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.9</version> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}</outputDirectory> <excludeArtifactIds>junit</excludeArtifactIds> </configuration> </execution> </executions> </plugin>
mvn clean package
target
folder: java -jar project-with-executable-jar-1.0-SNAPSHOT.jar
C:projectsapache-maven-cookbookproject-with-executable-jar arget>java -jar project-with-executable-jar-1.0-SNAPSHOT.jar 06:40:18.437 [main] INFO com.packt.cookbook.App - Hello World
We have made the following configurations to the Maven JAR plugin in our pom
file:
We also added the copy-dependencies
goal of the Maven Dependency plugin to copy over the required dependencies to the folder where the executable JAR is generated.
When we then run the executable JAR, it uses the manifest file to determine the main class as well as the dependencies, loads them, and runs.
Let us look at the manifest file generated:
Evidently, for this to work, the executable JAR should be accompanied by the dependencies that it uses. In the Creating an assembly recipe in Chapter 11, Advanced Maven Usage, we will learn how to create an assembly with all the dependencies, which can be distributed more easily.
3.139.83.151