You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Maven默认应用编译成功但mvn exec:java执行失败求助

Maven exec:java 执行失败问题排查

问题描述

我尝试编译并运行默认的Maven应用,确认编译已成功,直接使用java命令可正常运行,但通过mvn exec:java执行时失败,即使指定-DmainClass=com.mycompany.app.App参数仍提示'mainClass参数缺失或无效'。

操作步骤

  • 使用命令创建项目:
    $ mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=demoapp -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    
  • 在pom.xml中修改编译器配置(使用JDK 21):
    <maven.compiler.source>1.9</maven.compiler.source>
    <maven.compiler.target>1.9</maven.compiler.target>
    
  • 执行mvn compile,编译成功
  • 进入target/classes目录执行java com.mycompany.app.App,输出Hello World!
  • 执行mvn exec:java,提示BUILD FAILURE,错误信息为:

    The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:3.1.0:java are missing or invalid

  • 执行mvn -DmainClass=com.mycompany.app.App exec:java,仍报相同错误

附当前pom.xml内容及项目目录结构,请问问题出在哪里?

问题原因及解决方法

核心原因:exec-maven-plugin版本参数变更

你使用的exec-maven-plugin 3.1.0版本,从该版本开始,命令行指定主类的参数名已从mainClass改为exec.mainClass,旧参数名不再被插件识别,所以会提示参数缺失。

另外,你的JDK版本是21,但pom中配置的编译source/target为1.9,版本不匹配可能引发潜在兼容性问题,建议同步调整。

解决办法

临时快速解决(命令行直接修改参数)

使用插件要求的新参数名执行命令:

mvn exec:java -Dexec.mainClass=com.mycompany.app.App

永久解决(配置到pom.xml)

在pom.xml的<build><plugins>节点中添加插件配置,后续直接执行mvn exec:java即可:

<build>
  <plugins>
    <!-- 修正编译版本配置,匹配JDK 21 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.11.0</version>
      <configuration>
        <source>21</source>
        <target>21</target>
        <release>21</release>
      </configuration>
    </plugin>
    <!-- 配置exec-maven-plugin指定主类 -->
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>exec-maven-plugin</artifactId>
      <version>3.1.0</version>
      <configuration>
        <mainClass>com.mycompany.app.App</mainClass>
      </configuration>
    </plugin>
  </plugins>
</build>

内容的提问来源于stack exchange,提问作者notaorb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 23:17:27