5

修复Spring Boot的Manifest无主函数错误 | baeldung

 1 year ago
source link: https://www.jdon.com/63921
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

修复Spring Boot的Manifest无主函数错误


每当我们在 Spring Boot 可执行文件 jar 中遇到“无主清单属性no main manifest attribute”消息时,那是因为我们缺少文件MANIFEST.MF中Main-Class元数据属性的声明,该文件位于META-INF文件夹下。
在这个简短的教程中,我们将了解问题的原因以及解决方法。

问题:
通常,如果我们从 Spring Initializr 中获取我们的pom,我们不会有任何问题。但是,如果我们通过将spring-boot-starter-parent添加到我们的pom.xml来手动构建我们的项目,我们可能会遇到这个问题。我们可以通过尝试干净地构建 jar 来复制它:

$ mvn clean package

运行 jar 时我们会遇到错误:

$ java -jar target\spring-boot-artifacts-2.jar
no main manifest attribute, in target\spring-boot-artifacts-2.jar

在这个例子中,MANIFEST.MF文件的内容是:

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven 3.6.3
Built-By: Baeldung
Build-Jdk: 11.0.13

使用 Maven 插件修复:
1. 添加插件
在这种情况下,最常见的问题是我们错过了将spring-boot-maven-plugin声明添加到我们的pom.xml文件中。
让我们使用plugins标签下的Main-Class声明将插件定义添加到我们的pom.xml中:

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <mainClass>com.baeldung.demo.DemoApplication</mainClass>
            <layout>JAR</layout>
        </configuration>
    </plugin>
</plugins>

但是,这可能不足以解决我们的问题。重建并运行 jar 后,我们可能仍会收到“无主要清单属性”消息。

让我们看看我们有哪些额外的配置和替代方案来解决这个问题。

2. Maven 插件执行目标
让我们将重新打包 目标添加到配置标记之后的spring-boot-maven-plugin声明中:

<executions>
    <execution>
        <goals>
            <goal>repackage</goal>
        </goals>
    </execution>
</executions>

3. Maven 属性和内联命令执行目标
或者,将属性start-class添加到我们的pom.xml文件的properties标记中,可以在构建过程中提供更大的灵活性:

<properties>
    <start-class>com.baeldung.demo.DemoApplication</start-class>
</properties>

现在,我们必须使用 Maven 内联命令spring-boot:repackage执行目标来构建 jar:

$ mvn package spring-boot:repackage

我们注意到Main-Class和Start-Class属性的存在:

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven 3.6.3
Built-By: Baeldung
Build-Jdk: 11.0.13
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.baeldung.demo.DemoApplication
Spring-Boot-Version: 2.7.5
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx
Spring-Boot-Layers-Index: BOOT-INF/layers.idx

现在执行 jar,“no main manifest attribute”消息问题不再出现,应用程序运行。

示例代码在 GitHub 上可用


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK