3-ways-to-run-java-main-from-maven



id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf


cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:


id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:



cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:


id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf


cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:


id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf id="twttrHubFrameSecure" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrameSecure" src="https://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;"> id="twttrHubFrame" allowtransparency="true" frameborder="0" scrolling="no" tabindex="0" name="twttrHubFrame" src="http://platform.twitter.com/widgets/hub.bd32c94b5665aa746e00aaa2cf9de3cf.html" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; position: absolute; top: -9999em; width: 10px; height: 10px;">

3 ways to run Java main from Maven

Overview

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 3 ways of using the maven exec plugin to run java, with code examples.

1) Running from Command line

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.

  1. mvn compile  

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

Without arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  
With arguments:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  
With runtime dependencies in the CLASSPATH:
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

2) Running in a phase in pom.xml

You can also run the main method in a maven phase. For example, you can run the CodeGenerator.main() method as part of the test phase.

  1. <build>  
  2.  <plugins>  
  3.   <plugin>  
  4.    <groupId>org.codehaus.mojo</groupId>  
  5.    <artifactId>exec-maven-plugin</artifactId>  
  6.    <version>1.1.1</version>  
  7.    <executions>  
  8.     <execution>  
  9.      <phase>test</phase>  
  10.      <goals>  
  11.       <goal>java</goal>  
  12.      </goals>  
  13.      <configuration>  
  14.       <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  15.       <arguments>  
  16.        <argument>arg0</argument>  
  17.        <argument>arg1</argument>  
  18.       </arguments>  
  19.      </configuration>  
  20.     </execution>  
  21.    </executions>  
  22.   </plugin>  
  23.  </plugins>  
  24. </build>  

To run the exec plugin with above configuration, simply run the corresponding phase.

  1. mvn test  

3) Running in a profile in pom.xml

You can also run the main method in a different profile. Simply wrap the above config in the <profile> tag.

  1. <profiles>  
  2.  <profile>  
  3.   <id>code-generator</id>  
  4.   <build>  
  5.    <plugins>  
  6.     <plugin>  
  7.      <groupId>org.codehaus.mojo</groupId>  
  8.      <artifactId>exec-maven-plugin</artifactId>  
  9.      <version>1.1.1</version>  
  10.      <executions>  
  11.       <execution>  
  12.        <phase>test</phase>  
  13.        <goals>  
  14.         <goal>java</goal>  
  15.        </goals>  
  16.        <configuration>  
  17.         <mainClass>com.vineetmanohar.module.CodeGenerator</mainClass>  
  18.         <arguments>  
  19.          <argument>arg0</argument>  
  20.          <argument>arg1</argument>  
  21.         </arguments>  
  22.        </configuration>  
  23.       </execution>  
  24.      </executions>  
  25.     </plugin>  
  26.    </plugins>  
  27.   </build>  
  28.  </profile>  
  29. </profiles>  

To call the above profile, run the following command:

  1. mvn test -Pcode-generator  

Advanced options:

You can get a list of all available parameters by typing:

  1. mvn exec:help -Ddetail=true -Dgoal=java  

arguments (exec.arguments)

 The class arguments.

classpathScope (exec.classpathScopeDefault: compile)

 Defines the scope of the classpath passed to the plugin. Set to
 compile, test, runtime or system depending on your needs

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  1. [ERROR] BUILD ERROR  
  2. [INFO] ------------------------------------------------------------------------  
  3. [INFO] Failed to configure plugin parameters for: org.codehaus.mojo:exec-maven-plugin:1.1.1  
  4. on the command line, specify: '-Dexec.arguments=VALUE'  
  5. Cause: Cannot assign configuration entry 'arguments' to 'class [Ljava.lang.String;' from '${exec.arguments}',   
  6. which is of type class java.lang.String  
  7. [INFO] ------------------------------------------------------------------------  
  8. [INFO] Trace  
  9. org.apache.maven.lifecycle.LifecycleExecutionException: Error configuring: org.codehaus.mojo:exec-maven-plugin.   
  10. Reason: Unable to parse the created DOM for plugin configuration  
  11.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:588)  
  12.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:513)  
  13.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:483)  
  14.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:331)  
  15.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:292)  
  16.  at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)  
  17.  at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)  
  18.  at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)  
  19.  at org.apache.maven.cli.MavenCli.main(MavenCli.java:301)  

Solution

exec.arguments was used before version 1.1 of the exec plugin, it did not support conversion of command line String to String[] array.

  1. If possible upgrade to 1.1 or later and use exec.args instead of exec.arguments.
  2. If you can't upgrade the plugin version, you can still use command line arguments with a profile and use multiple <argument> tags associated in the pom.xml

References

    

name="f12f15e27c" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:like Facebook Social Plugin" src="http://www.facebook.com/plugins/like.php?app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2F6brUqVNoWO3.js%3Fversion%3D41%23cb%3Df2e7c6ef94%26domain%3Dwww.vineetmanohar.com%26origin%3Dhttp%253A%252F%252Fwww.vineetmanohar.com%252Ff26632479%26relation%3Dparent.parent&container_width=0&href=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&layout=button_count&locale=en_US&sdk=joey&send=false&show_faces=false" style="position: absolute; border-style: none; visibility: visible; width: 78px; height: 20px;">
 
frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1443515785671" name="I0_1443515785671" src="https://apis.google.com/se/0/_/+1/fastbutton?usegapi=1&size=medium&count=false&origin=http%3A%2F%2Fwww.vineetmanohar.com&url=http%3A%2F%2Fwww.vineetmanohar.com%2F2009%2F11%2F3-ways-to-run-java-main-from-maven%2F&gsrc=3p&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.vi.5hpnngUu-2A.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPTSqOYkaP1U6q4oCWtRMtgv6oPUA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1443515785671&parent=http%3A%2F%2Fwww.vineetmanohar.com&pfname=&rpctoken=42774078" data-gapiattached="true" title="+1" style="position: static; top: 0px; width: 32px; margin: 0px; border-style: none; left: 0px; visibility: visible; height: 20px;">

Related posts:

  1. The plugin ‘org.codehaus.mojo:selenium-maven-plugin’ does not exist or no valid version could be found
  2. Tweet your builds with Maven Twitter Plugin
  3. How to automate project versioning and release with Maven
  4. JAXB code snippets for beginners
  5. How to display maven project version in your webapp

21 comments to 3 ways to run Java main from Maven

  • Erik

    Don’t forget the Maven CLI method, it’s waaay faster than anything else!

  • vineet

    If you get the following error:
    Project ID: org.codehaus.mojo:maven-exec-plugin
    POM Location: ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom
    Reason: Not a v4.0.0 POM. for project org.codehaus.mojo:maven-exec-plugin at ~/.m2/repository/org/codehaus/mojo/maven-exec-plugin/1.1.1/maven-exec-plugin-1.1.1.pom

    and the following content in the file: ~/.m2/repository/org/apache/maven/plugins/maven-exec-plugin/maven-metadata-java.net.xml


    < !DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    Moved Permanently

    The document has moved here.


    Apache Server at maven-repository.dev.java.net Port 443


    Try the full command line:
    mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

  • Kamal

    Thanks folks. I am using the maven-exec plugin to run jarsigner and get surprised by the following:
    jarsigner ${project.build.directory}\jarname bla bla bla

    However, assume the value of ${project.build.directory} is C:\somedir\somesubdir, the exec is ripping off all the slashes in the build directory path and tries to pass”

    C:somedirsomeubdir

    Any ideas?
    Thanks a log

  • @Kamal try forwards slashes instead of backslashes

  • Tim

    So how would I java my -javaagent= arg.. exec.args gives it to the class being run…

  • Tim

    Oh I see now. Run export MAVEN_OPTS=-javaagent:.. first.

  • Jesse Glick

    Consider using exec:exec rather than exec:java for running your own project, unless the code in question is really a bit of build tool. Discussed here: http://maven.40175.n5.nabble.com/Call-System-setProperty-quot-java-awt-headless-quot-true-td3383750.html#a3388567

    (Hi Vineet!)

  • norman rm

    thanks

  • Max Mohave

    Dear Vineet:

    thank, I used your info to run my new application by MVN command line. Do you use an IDE with MAVEN to run and if so which one. And lastly, can you tell me how you would use the equivalent of mvn org.codehaus.mojo:exec-maven-plugin:1.1.1:java -Dexec.mainClass=com.vineetmanohar.module.Main

    to run in that IDE?

    Thanks so much.

  • vineet

    I use Eclipse. I first run “mvn eclipse:eclipse” to export the project into eclipse format. Then import the project by using File -> Import -> Import existing project.

    However, I use mvn from command line and not from inside the IDE.

    There are eclipse plugins for maven (like m2eclipse) that you can use from inside Eclipse but I don’t use them.

  • Max Mohave

    Thank you. I appreciate your skill and time.
    Sincerely, Max

  • Finn

    Highest quality blog post ever, exactly what I needed. Thank you.

  • Thanks. Combined with your post and the maven doco, it took me about 10 minutes to have it working and documented.

  • Akilan

    Thanks Vineet. Wonderful blog and exactly what I searched for.

  • Anil Kesariya

    hello i m anil

    i m first time working with maven.. so i dont that how should we work with it , i got lession that how we can generate jar file from our java file using maven
    so please tell me that how should i work with it..i have only one day dead line..

  • Tensy

    Hi Vineet, This post is really useful.
    However, when I try to run the command, I see the following.
    Command: mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -e -Dexec.mainClass=com.myclass.Wsdl2XsdConverter

    An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    INFO] Trace
    org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.myclass.Wsdl2XsdConverter
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:703)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:553)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:523)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:371)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:332)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:181)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:356)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:137)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:356)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:592)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.qpass.googlecarrierbilling.Wsdl2XsdConverter
    at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:483)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:678)
    … 16 more
    Caused by: java.lang.ClassNotFoundException: com.myclass.Wsdl2XsdConverter
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284)
    at java.lang.Thread.run(Thread.java:595)

    I run the mvn compile command also prior to running the above mentioned mvn command.
    Any help is greatly appreciated.

  • vineet

    Looks right to me.

    I would try the following:
    1) Try mvn -X to generate more debug info.
    2) Also try the other approach as described in section 2) above: “Running in a phase in pom.xml”, see if that works.

  • Ramaraj

    Thank you for your time and effort to create this blog. I have got more info than what i need.

  • andres

    Thanks a lot. but how to package all depedencies into single jar

  • Dev

    Content is very helpful.
    Please tell me how can i debug while executing my main class. I used Eclipse.

    Thanks

  • Yashaswini

    Hi,
    I need to trigger a makefile through Maven. Could someone please tell how this can be done? Can exec-maven-plugin be used to execute a makefile? When I use exec-maven-plugin to execute my makefile, I get the following error:
    [INFO] — exec-maven-plugin:1.1:exec (buildlib) @ nativeTestProjectMaven —
    [INFO] ‘”C:\Program Files\apache-maven-3.0.4\TestProjectMaven\src\main\native\ma
    kefile”‘ is not recognized as an internal or external command,
    [INFO] operable program or batch file.

Leave a Reply

  

  

  

You can use these HTML tags

name="fb_xdm_frame_http" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_http" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="http://static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;"> name="fb_xdm_frame_https" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" id="fb_xdm_frame_https" aria-hidden="true" title="Facebook Cross Domain Communication Frame" tabindex="-1" src="https://s-static.ak.facebook.com/connect/xd_arbiter/6brUqVNoWO3.js?version=41#channel=f26632479&origin=http%3A%2F%2Fwww.vineetmanohar.com" style="border-style: none;">
name="oauth2relay651382484" id="oauth2relay651382484" src="https://accounts.google.com/o/oauth2/postmessageRelay?parent=http%3A%2F%2Fwww.vineetmanohar.com#rpctoken=784954501&forcesecure=1" tabindex="-1" style="font-family: tahoma, arial, sans-serif; font-size: 13px; text-align: center; width: 1px; height: 1px; position: absolute; top: -100px;">
ShareThis Copy and Paste
- See more at: http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/#sthash.T70JUj6V.dpuf

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:

cleanupDaemonThreads (exec.cleanupDaemonThreads)

 Wether to interrupt/join and possibly stop the daemon threads upon
 quitting.  If this is false, maven does nothing about the daemon threads.
 When maven has no more work to do, the VM will normally terminate any
 remaining daemon threads.
 In certain cases (in particular if maven is embedded), you might need to
 keep this enabled to make sure threads are properly cleaned up to ensure
 they don't interfere with subsequent activity. In that case, see
 daemonThreadJoinTimeout and stopUnresponsiveDaemonThreads for further
 tuning.

commandlineArgs (exec.args)

 Arguments for the executed program

daemonThreadJoinTimeout (exec.daemonThreadJoinTimeoutDefault: 15000)

 This defines the number of milliseconds to wait for daemon threads to quit
 following their interruption. This is only taken into account if
 cleanupDaemonThreads is true. A value <=0 means to not timeout (i.e. wait
 indefinitely for threads to finish). Following a timeout, a warning will
 be logged. Note: properly coded threads should terminate upon interruption
 but some threads may prove problematic: as the VM does interrupt daemon
 threads, some code may not have been written to handle interruption
 properly. For example java.util.Timer is known to not handle interruptions
 in JDK <= 1.6. So it is not possible for us to infinitely wait by default
 otherwise maven could hang. A sensible default value has been chosen, but
 this default value may change in the future based on user feedback.

executableDependency

 If provided the ExecutableDependency identifies which of the plugin
 dependencies contains the executable class. This will have the affect of
 only including plugin dependencies required by the identified
 ExecutableDependency.
 If includeProjectDependencies is set to true, all of the project
 dependencies will be included on the executable's classpath. Whether a
 particular project dependency is a dependency of the identified
 ExecutableDependency will be irrelevant to its inclusion in the classpath.

includePluginDependencies (exec.includePluginDependencies, Default: false)

 Indicates if this plugin's dependencies should be used when executing the
 main class. This is useful when project dependencies are not appropriate. Using
 only the plugin dependencies can be particularly useful when the project is not
 a java project. For example a mvn project using the csharp plugins only expects
 to see dotnet libraries as dependencies.

includeProjectDependencies (exec.includeProjectDependenciesDefault: true)

 Indicates if the project dependencies should be used when executing the
 main class.

mainClass (exec.mainClass)

 The main class to execute.

sourceRoot (sourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled. Use this if your plugin generates source code.

stopUnresponsiveDaemonThreads (exec.stopUnresponsiveDaemonThreads)

 Wether to call Thread.stop() following a timing out of waiting for an
 interrupted thread to finish. This is only taken into account if
 cleanupDaemonThreads is true and the daemonThreadJoinTimeout threshold has
 been reached for an uncooperative thread. If this is false, or if
 Thread.stop() fails to get the thread to stop, then a warning is logged
 and Maven will continue on while the affected threads (and related objects
 in memory) linger on. Consider setting this to true if you are invoking
 problematic code that you can't fix. An example is Timer which doesn't
 respond to interruption. To have Timer fixed, vote for this bug.

systemProperties

 A list of system properties to be passed. Note: as the execution is not
 forked, some system properties required by the JVM cannot be passed here.
 Use MAVEN_OPTS or the exec:exec instead. See the user guide for more
 information.

testSourceRoot (testSourceRoot)

 This folder is added to the list of those folders containing source to be
 compiled for testing. Use this if your plugin generates test source code.

FAQ and Errors

Why do I get this error when specifying arguments to my main method:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值