ITKeyword,专注技术干货聚合推荐

注册 | 登录

3 ways to run Java main from Maven

wiksys 分享于 2013-09-12

推荐:"Could not find or load main class" in Hadoop or Java using Maven

最近在按照《hadoop权威指南》里的例子来学习hadoop,里面的例子通过eclipse可以运行,但一使用命令行就无法运行。。然后硬着头皮往下看,又出现了mvn命令,又看

2019阿里云全部产品优惠券(新购或升级都可以使用,强烈推荐)
领取地址https://promotion.aliyun.com/ntms/yunparter/invite.html

转载地址:http://www.vineetmanohar.com/2009/11/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:

view plain copy to clipboard print ?
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  

With arguments:

view plain copy to clipboard print ?
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  

With runtime dependencies in the CLASSPATH:

view plain copy to clipboard print ?
  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.

view plain copy to clipboard print ?
  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.

view plain copy to clipboard print ?
  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:

view plain copy to clipboard print ?
  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:

view plain copy to clipboard print ?
  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.

推荐:JAVA学习:maven开发环境快速搭建How to download J2EE API (javaee.jar) from Maven

http://tech.it168.com/a2011/1204/1283/000001283307.shtml 【IT168技术】最近,开发中要用到maven,所以对maven进行了简单的学习。因为有个maven高手在身边,

  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
,

转载地址:http://www.vineetmanohar.com/2009/11/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:

view plain copy to clipboard print ?
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main"  

With arguments:

view plain copy to clipboard print ?
  1. mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.args="arg0 arg1 arg2"  

With runtime dependencies in the CLASSPATH:

view plain copy to clipboard print ?
  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.

view plain copy to clipboard print ?
  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.

view plain copy to clipboard print ?
  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:

view plain copy to clipboard print ?
  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:

view plain copy to clipboard print ?
  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

推荐:解决Eclipse建立Maven项目后无法建立src/main/java 源文件夹的办法

  建立好一个Maven项目后,如果Java Resources资源文件下没有src/main/java文件夹,并且在手动创建这个文件时提示“已存在文件”。 这说明,在这个项目配置中已

转载地址:http://www.vineetmanohar.com/2009/11/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

相关阅读排行


用户评论

游客

相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。