Spring Boot应用的Unable to find main class异常详解

1. Spring Boot应用执行java -jar myApp.jar时,出现如下异常:

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.4.RELEASE:repackage (default) on project teac: 
Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.5.4.RELEASE:repackage failed: 
Unable to find main class -> [Help 1]


Spring Boot应用的pom.xml文件中相关配置如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath></relativePath>
</parent>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


2. 异常分析

构建过程能够顺利完成,说明Spring Boot应用的代码编译没有问题。

下面看看Spring Boot应用的启动过程。对于以“java -jar”方式启动Spring Boot应用,Spring Boot Loader启动时,首先扫描Spring Boot应用的根路径下的配置类(@Configuration修饰的类),该类中往往定义main()函数,并在main()函数中调用SpringApplication.run(...)以启动应用,如下所示。

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}
或者

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}

如果发现有且仅有一个这样的类,则执行其main()函数启动Spring Boot应用。

如果没有发现任何这样的类,或者发现了多个这样的类,则Spring Boot Loader就无法确定以哪个为准,从而抛出了上述异常。


3. 解决方案

首先,作为一个Spring Boot应用,不能没有配置类。

其次,Spring Boot应用中可能在为不同的环境定义的多个不同的配置类,究竟以哪个为准启动应用,可以配置pom.xml文件如下以解决。

<properties>
    <start-class>com.ericsson.MyApplication</start-class>
</properties>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值