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

来源:互联网 发布:表白网站整站源码 编辑:程序博客网 时间:2024/06/16 11:17

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@ComponentScanpublic class MyApplication {    public static void main(String[] args) {        SpringApplication.run(MyApplication.class, args);    }}
或者

@SpringBootApplicationpublic 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>


阅读全文
1 0
原创粉丝点击