如何告诉Spring Boot哪个主类用于可执行jar?

问题描述 投票:159回答:9
Execution default of goal 
org.springframework.boot:spring-boot-maven-plugin:1.0.1.RELEASE:repackage 
failed: 
Unable to find a single main class from the following candidates

我的项目有多个类使用main方法。我如何告诉Spring Boot Maven插件它应该用作哪个类作为主类?

java spring maven executable-jar spring-boot
9个回答
243
投票

在你的pom中添加你的起始类:

<properties>
    <!-- The main class to start by executing java -jar -->
    <start-class>com.mycorp.starter.HelloWorldApplication</start-class>
</properties>

122
投票

对于那些使用Gradle(而不是Maven)的人:

springBoot {
    mainClass = "com.example.Main"
}

66
投票

如果你不使用spring-boot-starter-parent pom,那么从Spring documentation

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>1.1.3.RELEASE</version>
    <configuration>
        <mainClass>my.package.MyStartClass</mainClass>
        <layout>ZIP</layout>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

12
投票

对于那些使用Gradle(而不是Maven)的人,引用here

也可以使用任务的mainClassName属性显式配置主类:

bootJar {
    mainClassName = 'com.example.ExampleApplication'
}

或者,可以使用Spring Boot DSL的mainClassName属性在项目范围内配置主类名:

springBoot {
    mainClassName = 'com.example.ExampleApplication'
}

10
投票

如果你在你的pom中使用spring-boot-starter-parent,你只需将以下内容添加到你的pom中:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

然后做你的mvn包。

this Spring docs page

这里一个非常重要的方面是提到目录结构必须是src / main / java / nameofyourpackage


3
投票

我在pom.xml中尝试了以下代码,它对我有用

<build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <mainClass>myPackage.HelloWorld</mainClass> 
        </configuration>
    </plugin>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <fork>true</fork>
            <executable>D:\jdk1.8\bin\javaw.exe</executable>
        </configuration>
    </plugin>
</plugins>


1
投票

我已经重命名了我的项目,它仍然在构建路径上找到旧的Application类。我在'build'文件夹中删除了它,一切都很好。


1
投票

从Spring Boot 1.5开始,您可以完全忽略pom或build.gradle中容易出错的字符串文字。重新打包工具(通过maven或gradle插件)将为您选择使用@SpringBootApplication注释的工具。 (详情请参阅此问题:https://github.com/spring-projects/spring-boot/issues/6496


0
投票

在没有明确指定main-class时,已经看到了Java 1.9和Spring Boot 1.5.x的这个问题。

使用Java 1.8,它能够找到没有显式属性的main-class,并且'mvn package'可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.