Search code examples
javamavenmaven-2maven-exec-plugin

run main class of Maven project


I've created a simple console Java application that is built with Maven. Is there a way that the main class (which doesn't require any arguments) can be run from the command-line using a maven command like:

mvn run-app com.example.MainClass

Solution

  • Try the maven-exec-plugin. From there:

    mvn exec:java -Dexec.mainClass="com.example.Main"
    

    This will run your class in the JVM. You can use -Dexec.args="arg0 arg1" to pass arguments.

    If you're on Windows, apply quotes for exec.mainClass and exec.args:

    mvn exec:java -D"exec.mainClass"="com.example.Main"
    

    If you're doing this regularly, you can add the parameters into the pom.xml as well:

    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>exec-maven-plugin</artifactId>
      <version>1.2.1</version>
      <executions>
        <execution>
          <goals>
            <goal>java</goal>
          </goals>
        </execution>
      </executions>
      <configuration>
        <mainClass>com.example.Main</mainClass>
        <arguments>
          <argument>foo</argument>
          <argument>bar</argument>
        </arguments>
      </configuration>
    </plugin>