Making executable jar using maven

I was trying something out the other day and wanted to write a really simple application. So I created a simple application backed by Maven.

Now I could run the jar file that maven built using the standard -e flag that lets java know the entry point but all that is too main stream. I wanted maven to handle that for me.

After doing some googling, I found a plugin provided by codehaus. This one allowed me to run the application through maven. As you can see below, the configuration is quite simple.

1

2

3

4

5

6

7

8

9

10

11

12

<build>

..

<plugin>

<groupId>org.codehaus.mojo</groupId>

<artifactId>exec-maven-plugin</artifactId>

<version>1.2.1</version>

<configuration>

<mainClass>com.manthanhd.cli.RunCli</mainClass>

</configuration>

</plugin>

..

</build>

Make sure you update the value inside mainClass with fully qualified name of your class that you want to run. This class must have a public static void main method in it.

Once you are happy with the configuration, you can run your application by executing the following in your terminal

1

mvn exec:java

While this is great, I cannot run the jar on its own on a server somewhere. If I wanted to, I’d have to get the source code with maven and then run it using the above command. Thats sub-optimal. So I went googling again.

Finally, I found this wonderful plugin provided by our friends at Apache. This is the maven-jar-plugin. This is a standard jar plugin but one of its features is ability to specify a mainClass attribute – just like the codehaus plugin. But unlike the codehaus plugin, I can run the jar as a standalone application without needing to pass in any other flags or parameters indicating the main class.

Here’s the maven build plugin configuration to use the maven-jar-plugin.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<build>

...

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-jar-plugin</artifactId>

<configuration>

<archive>

<manifest>

<addClasspath>true</addClasspath>

<mainClass>com.manthanhd.cli.RunCli</mainClass>

</manifest>

</archive>

</configuration>

</plugin>

...

</build>

As it is standard with maven, package up your application using:

Shell

1

mvn clean install

If the build was successful, just run your jar file using standard java -jar path/to/app.jar command. In my case, I ran: