解决 java -jar 报错:xxx.jar 中没有主清单属性
问题复现
在使用 java -jar xxx.jar 命令运行 Java 应用程序时,遇到了以下错误:
xxx.jar 中没有主清单属性

这个错误表示 JAR 文件缺少必要的启动信息,Java 虚拟机无法找到应用程序的入口点。本文将介绍该错误的原因以及如何通过修改 pom.xml 文件来解决。
错误原因
当你使用 java -jar 命令运行一个 JAR 文件时,Java 虚拟机会在该 JAR 的 META-INF/MANIFEST.MF 文件中查找 Main-Class 属性,以确定应用程序的入口点。如果该属性缺失,或者指定的主类不存在,就会导致上述错误。
解决方法
要解决这个问题,需要在项目的 pom.xml 文件中配置 Maven 插件,以正确生成包含 Main-Class 属性的可执行 JAR 文件。
 步骤一:在 pom.xml 中添加或修改 <build> 配置
在你的 pom.xml 文件中,找到或添加 <build> 部分。

然后修补上以下内容:
<build>
    <plugins>
        <!-- Maven Compiler Plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        <!-- Spring Boot Maven Plugin -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>${spring-boot.version}</version>
            <configuration>
                <mainClass>xxx.xxx.xxx.xxxApplication</mainClass>
                <skip>false</skip>
            </configuration>
            <executions>
                <execution>
                    <id>repackage</id>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
配置说明:
- Maven Compiler Plugin:指定了 Java 源代码和目标版本,以及编码格式。
- Spring Boot Maven Plugin:
- <mainClass>:指定应用程序的主类,必须包含- main方法。请将- xxx.xxx.rxxxdc.xxxApplication替换为你实际的主类路径。
- <skip>false</skip>:确保插件不会被跳过,默认情况下可以省略该配置。
- <executions>:指定在构建过程中执行- repackage目标,重新打包 JAR 文件。
 
步骤二:重新构建项目
在项目根目录下,运行以下命令:
mvn clean package
这将清理项目并重新打包,生成的 JAR 文件通常位于 target 目录下,名称类似于 xxx.jar。
也可以在 IDEA 的 Maven 菜单里右键操作。
先运行 clean。

再运行 package。

步骤三:运行生成的 JAR 文件
使用以下命令运行应用程序:
java -jar target/xxx.jar
如果配置正确,应用程序应该能够正常启动,不再出现 “没有主清单属性” 的错误。

注意事项
- 确认主类存在且路径正确:确保你的主类(例如 xxxApplication)存在,并且位于指定的包路径下(例如xxx.xxx.xxx)。
- 版本一致性:spring-boot-maven-plugin的版本应与 Spring Boot 的版本一致,通常使用${spring-boot.version}引用。
- 避免插件被跳过:确保 <skip>false</skip>,避免插件被跳过。
- 重新打包:确保 <executions></executions>标签及内部的repackage属性存在。
结论
通过在 pom.xml 文件中正确配置 Maven 插件,可以解决 java -jar 命令运行时出现的 “没有主清单属性” 的错误。关键是确保生成的 JAR 文件包含正确的 Main-Class 属性,以及所有必要的依赖项。
希望本篇文章能够帮助你解决问题,顺利运行你的 Java 应用程序。
- 点赞
- 收藏
- 关注作者
 
             
           
评论(0)