spring boot 项目 mvn clean install 报 "Unable to find main class" 的解决方法

按照步骤来总会解决的

  • 检查pom.xml中是否加入了spring boot maven插件
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

  • 检查项目中是否有main方法并且main方法上是否有 @SpringBootApplication 注解
mvn 会自动在项目中早main方法加入到jar中的主清单属性中
如果没有没有找到main方法,当你打包的时候就会报错  "Unable to find main class"
  • 检查项目中是否有多个main方法
如果项目中存在多个main方法,mvn会不知道你究竟想要用哪个main方法作为jar包的清单属性
所以这个时候你必须要在pom.xml文件中指定一个 mainClass 

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>com.**.**.testApplication</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>
  • 检查项目结构
mvn 之所以能找到项目中的main方法,是因为mvn有一套自己的项目结构
例如:
source (源码) 目录:
      /src/main/java
resources (所需资源) 目录:
     /src/main/resources

所以需要检查我们的项目结构是否是按照maven的默认项目结构的标准
在IDEA中,如果项目结构不是这种默认的结构的话,我们需要在IDEA中指定source或resources目录
如果已经按照这种默认项目结构的标准导入IDEA是不需要手动指定source的
同理,如果不按照这种默认标准创建项目mvn默认也不认识项目中的source
所以我们也可以通过如下配置指定source和resource目录


<build>
   
   <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
   <resources>
      <resource>
        <directory>${project.basedir}/src/main/resources</directory>
      </resource>
    </resources>

    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>com.**.**.testApplication</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>


但是不推荐修改默认的项目结构,还是推荐使用maven提供的默认项目结构来创建项目

https://maven.apache.org/pom.html

posted @ 2020-04-23 14:04  jasondayee  阅读(1561)  评论(0编辑  收藏  举报