AWS EC2 Linux运行Gradle多项目Jar包提示无法找到或加载主类
问题原因分析
- 你当前打包出来的
*-plain.jar是Gradle原生构建的普通Jar包,不是Spring Boot可执行的Fat Jar,既没有包含项目依赖,也没有正确打包子模块中的主类 - 主类
com.example.DemoApplication存放在web子模块下,你将主类声明、Spring Boot插件、全局依赖都放在根build.gradle不符合Gradle多项目配置规范,根项目本身没有主类代码,打包时自然找不到对应类 - 多项目结构下,应该将公共配置抽离到根build.gradle,子模块单独配置自身属性,可执行Jar的构建逻辑应该放在
web子模块中,而非根目录
解决步骤
步骤1:调整根目录build.gradle配置
将根目录配置修改为公共配置形态,移除主类声明、Spring Boot应用相关的专属配置,仅保留子模块共用的通用配置:
plugins { id 'org.springframework.boot' version '2.6.1' apply false id 'io.spring.dependency-management' version '1.0.11.RELEASE' apply false id 'java' } // 所有子模块通用配置 subprojects { group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' apply plugin: 'java' apply plugin: 'io.spring.dependency-management' repositories { mavenCentral() } dependencyManagement { imports { mavenBom "org.springframework.boot:spring-boot-dependencies:2.6.1" } } configurations { compileOnly { extendsFrom annotationProcessor } } dependencies { compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' } test { useJUnitPlatform() } }
注意:根目录需要存在
settings.gradle文件,声明包含的子模块:rootProject.name = 'demo' include 'core' include 'web'
步骤2:配置core子模块的build.gradle
core作为公共依赖模块,仅声明自身所需的业务依赖即可:
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-ldap' implementation 'org.springframework.boot:spring-boot-starter-hateoas' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' implementation 'org.springframework.boot:spring-boot-starter-security' runtimeOnly 'mysql:mysql-connector-java' runtimeOnly 'org.postgresql:postgresql' }
步骤3:配置web子模块的build.gradle
web作为启动入口模块,引入Spring Boot插件,声明主类,同时依赖core子模块:
plugins { id 'org.springframework.boot' } dependencies { // 依赖core子模块 implementation project(':core') // web模块自身专属依赖 implementation 'org.springframework.boot:spring-boot-starter-web' developmentOnly 'org.springframework.boot:spring-boot-devtools' } // 配置Spring Boot可执行Jar的主类 bootJar { mainClass = 'com.example.DemoApplication' }
步骤4:重新打包启动
- 在项目根目录执行打包命令:
./gradlew bootJar - 打包完成后,可执行Jar的存储路径为
web/build/libs/web-0.0.1-SNAPSHOT.jar,请勿使用带-plain后缀的普通Jar包 - 将该Jar上传到EC2后,执行启动命令:
java -jar /home/ec2-user/web-0.0.1-SNAPSHOT.jar即可正常启动
内容的提问来源于stack exchange,提问作者Jeka_FRI
相关产品推荐
相关产品推荐

