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

- 日理万妓 2022-06-12 08:30 368阅读 0赞
  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文件中相关配置如下:

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.5.4.RELEASE</version>
  5. <relativePath></relativePath>
  6. </parent>
  7. <build>
  8. <plugins>
  9. <plugin>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-maven-plugin</artifactId>
  12. </plugin>
  13. </plugins>
  14. </build>
  1. 异常分析

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

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

  1. @Configuration
  2. @EnableAutoConfiguration
  3. @ComponentScan
  4. public class MyApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(MyApplication.class, args);
  7. }
  8. }

或者

  1. @SpringBootApplication
  2. public class MyApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(MyApplication.class, args);
  5. }
  6. }

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

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

  1. 解决方案

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

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

  1. <properties>
  2. <start-class>com.ericsson.MyApplication</start-class>
  3. </properties>

发表评论

表情:
评论列表 (有 0 条评论,368人围观)

还没有评论,来说两句吧...

相关阅读