Configuring Maven to run your Java application


Recently I was working on a project using Maven, and I really wanted to be able to run the project easily without needing to worry about all the classpath entries.

Turns out it is relatively easy to set up Maven to run your project for you and to automatically handle providing the right classpath for your code and all the dependencies.

Main Article

I created a simple Maven JAR project using an archetype as shown below:

$mvn archetype:create 

Then I edited the pom.xml file in the myproject directory.  I added the entries shown in red.  These tell Maven to compile the project using Java 1.6, and the name of the main class for the project.

<project xmlns="" 

Having done this, I can then build and then run the project by simply typing these two commands:

$ mvn package
$ mvn exec:java
Hello World!

There will be a bunch of Maven messages too, but in the middle there you can see the output from the project – “Hello World!” in this case.  This example is just running the that was generated by Maven.  In your project, this class might start up a User Interface, or run any number of tasks.  It probably does a little more than printing “Hello World!”

[Updated Jan 7, 2011] This approach will run your application in the same process that Maven is running in, which may or may not be acceptable.  If you want to run it in a different process, you can modify the plugin configuration section to something more like this:


Then use the goal:

mvn exec:exec

This will execute the JVM in a new process and allow you to pass in whatever arguments you like.  Notice the empty classpath tag.  This will insert the correct runtime classpath for you based on the dependencies in the pom.xml.

Add Your Comment