How to Run “Execute” Java Main Class Using Maven Command

If you create a java project using Maven you can run it using Maven.

Objective:

  • How to run java main class using Maven?

Environment:

  • Maven

( 1 ) The Command

project_folder>mvn exec:java

( 2 ) pom.xml “needs to know about the main class

  • As we can see from the command we did not mention the main class, so how Maven knows which class to run? The answer in the pom.xml.
  • We need to add some instruction to the pom.xml to be able to execute the main class.
  • We need to add the below xml segment to the pom.xml.
...
<build>
    <plugins>
    	<plugin>
      	<artifactId>maven-compiler-plugin</artifactId>
      	<version>2.0.2</version>
      	<configuration>
        		<source>1.6</source>
        		<target>1.6</target>
      	</configuration>
     </plugin>
     	<plugin>
      	<groupId>org.codehaus.mojo</groupId>
      	<artifactId>exec-maven-plugin</artifactId>
      	<configuration>
             <mainClass>com.hmkcode.MainClassName</mainClass>
      	</configuration>
     	</plugin>
    </plugins>
   </build>
...

( 3 ) Example

If we have the following simple project with a main class “App.java”

“I have converted Maven project to Eclipse just to show the structure”

Now I will open the pom.xml file and add the above xml segment to the it.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hmkcode</groupId>
  <artifactId>maven-run-main-class</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>maven-run-main-class</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
    	<plugin>
      	<artifactId>maven-compiler-plugin</artifactId>
      	<version>2.0.2</version>
      	<configuration>
        		<source>1.6</source>
        		<target>1.6</target>
      	</configuration>
     </plugin>
     	<plugin>
      	<groupId>org.codehaus.mojo</groupId>
      	<artifactId>exec-maven-plugin</artifactId>
      	<configuration>
             <mainClass>com.hmkcode.App</mainClass>
      	</configuration>
     	</plugin>
    </plugins>
   </build>

</project>

Now, go to the project directory “maven-run-main-class” using the command prompt type the command:

..\maven-run-main-class>mvn exec:java

For more info about exec Maven plugin…