[java] Maven Run Project

Is there a Maven "phase" or "goal" to simply execute the main method of a Java class? I have a project that I'd like to test manually by simply doing something like "mvn run".

This question is related to java maven

The answer is


clean package exec:java -P Class_Containing_Main_Method command is also an option if you have only one Main method(PSVM) in the project, with the following Maven Setup.

Don't forget to mention the class in the <properties></properties> section of pom.xml :

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.main.class>com.test.service.MainTester</java.main.class>
</properties>

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <configuration>
           <mainClass>${java.main.class}</mainClass>
        </configuration>
</plugin>

STS Run Configuration along with above Maven Setup:

enter image description here


1. Edit POM.xml

Add the following property in pom.xml. Make sure you use the fully qualified class name (i.e. with package name) which contains the main method:

<properties>
        <exec.mainClass>fully-qualified-class-name</exec.mainClass>
</properties>

2. Run Command

Now from the terminal, trigger the following command:

mvn clean compile exec:java

NOTE You can pass further arguments via -Dexec.args="xxx" flag.


No need to add new plugin in pom.xml. Just run this command

mvn org.codehaus.mojo:exec-maven-plugin:1.5.0:java -Dexec.mainClass="com.example.Main" | grep -Ev '(^\[|Download\w+:)' 

See the maven exec plugin for more usage.


Give the Exec Maven plugin a try


The above mentioned answers are correct but I am simplifying it for noobs like me.Go to your project's pom file. Add a new property exec.mainClass and give its value as the class which contains your main method. For me it was DriverClass in mainpkg. Change it as per your project. enter image description here

Having done this navigate to the folder that contains your project's pom.xml and run this on the command prompt mvn exec:java. This should call the main method.