Spring Boot多模块项目无法找到主类问题求助
解决Spring Boot多模块Gradle项目主类定位问题
看起来你在Spring Boot多模块Gradle项目里踩了个常见的坑——主类定位混乱,只有pictures-service模块能正常指定主类对吧?问题出在你当前的根项目Gradle配置里直接启用了Spring Boot插件,这在多模块架构里是不合适的。我给你整理一套清晰的修复方案:
第一步:重构根项目的build.gradle
根项目应该只负责统一依赖版本管理和通用配置,不要直接应用Spring Boot插件。修改后的配置如下:
buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.2.RELEASE") } } plugins { id 'java' id 'java-library' id 'idea' id "io.spring.dependency-management" version "1.0.5.RELEASE" } version = '0.1.0' repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 ext { common = [ spring_web : 'org.springframework.boot:spring-boot-starter-web:2.0.2.RELEASE', spring_rest : 'org.springframework.boot:spring-boot-starter-data-rest:2.0.2.RELEASE', spring_mongo : 'org.springframework.boot:spring-boot-starter-data-mongodb:2.0.2.RELEASE', spring_test : 'org.springframework.boot:spring-boot-starter-test' ] test = [ junit: 'junit:junit:4.12' ] } // 用Spring Boot BOM统一所有模块的依赖版本,避免版本冲突 dependencyManagement { imports { mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES } }
第二步:单独配置pictures-service模块的build.gradle
只有包含主启动类的pictures-service模块需要应用Spring Boot插件,在它的单独配置文件里做如下修改:
plugins { id 'org.springframework.boot' version "2.0.2.RELEASE" id 'java' id 'idea' } bootJar { baseName = 'com.bachadiff.pictures-service' version = '0.1.0' // 确保这里的主类路径和你的实际包结构完全匹配 mainClassName = 'com.bachadiff.application.Application' } dependencies { // 依赖你的业务实现模块 api project(':pictures-service-impl') // 因为根项目已经用BOM管理版本,这里可以直接写依赖短名 implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' testImplementation 'org.springframework.boot:spring-boot-starter-test' }
第三步:规范其他模块(如pictures-service-impl)的配置
其他业务模块只需要作为普通Java库存在,不需要Spring Boot插件,示例配置如下:
plugins { id 'java-library' id 'idea' } dependencies { // 按需添加业务需要的依赖,比如MongoDB的API api 'org.springframework.boot:spring-boot-starter-data-mongodb' testImplementation 'org.springframework.boot:spring-boot-starter-test' }
为什么这样修改?
- 根项目通过
dependency-management插件导入Spring Boot的BOM,让所有模块共享统一的依赖版本,彻底避免版本冲突问题。 - 只有包含主启动类的模块才启用Spring Boot插件,这样Gradle只会把这个模块打包成可执行的Spring Boot JAR,其他模块作为普通类库被依赖,不会干扰主类定位。
- 明确在
bootJar块里指定mainClassName,确保Spring Boot能精准找到你的启动类,完全符合你当前的路径pictures-service/src/main/com/bachadiff/application/Application.java(注意包名对应com.bachadiff.application)。
内容的提问来源于stack exchange,提问作者Fernando Ania
相关产品推荐
相关产品推荐

