Run Java main from Maven from Command line

By | September 7, 2014

Maven exec plugin lets you run the main method of a Java class in your project, with the project dependencies automatically included in the classpath.
This article show you a way of using the maven exec plugin to run java, with code examples.

Complile the code

Since you are not running your code in a maven phase, you first need to compile the code. Remember exec:java does not automatically compile your code, you need to do that first.

mvn compile

Running from Command line

Once your code is compiled, the following command runs your class

1) Without arguments

mvn exec:java -Dexec.mainClass="com.pengyifan.FooMain"  

2) With arguments:

mvn exec:java -Dexec.mainClass="com.pengyifan.FooMain" /
  -Dexec.args="arg0 arg1 arg2"

Config Maven

When Maven starts-up command, it reads two files /etc/mavenrc and ~/.mavenrc.
So we can setup maven settings there.
For example, to switch java to version 8, we can add the following to ~/.mavenrc

export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/"

To setup the heap size of JVM, add

export MAVEN_OPTS="-Xmx3G"

Leave a Reply

Your email address will not be published. Required fields are marked *