SpringBoot3多模块(Java9)项目RestTemplateBuilder依赖配置问题
解决多模块Spring Boot 3模块化应用中RestTemplateBuilder依赖配置问题
问题根源
在模块化项目中,RestTemplateBuilder的自动配置逻辑来自spring-boot-autoconfigure模块,而非仅spring-boot-starter-web。你的remote模块未在module-info.java中声明对该模块的依赖,同时模块化环境下Spring自动配置需要通过反射访问代码,因此还需开放对应包给自动配置模块。
此外当前配置存在两处冗余:
remote模块重复依赖了spring-web(spring-boot-starter-web已包含该依赖)- 所有子模块都应用了
org.springframework.boot插件,这对库类型的子模块(如remote、core、api)完全不必要
具体修复步骤
1. 调整主项目的插件应用范围
编辑主项目build.gradle,将allprojects块中的apply plugin: 'org.springframework.boot'移除,仅在主项目保留该插件:
plugins { id 'java' id 'org.springframework.boot' version '3.2.0-SNAPSHOT' id 'io.spring.dependency-management' version '1.1.2' } group = 'com.mrv' version = '0.0.1-SNAPSHOT' java { sourceCompatibility = '17' } configurations { compileOnly { extendsFrom annotationProcessor } } bootJar { mainClass = 'com.mrv.lendyourstocks.LendyourstocksApplication' } bootRun { mainClass = 'com.mrv.lendyourstocks.LendyourstocksApplication' } allprojects { apply plugin: 'java' apply plugin: 'io.spring.dependency-management' repositories { mavenCentral() maven { url 'https://repo.spring.io/milestone' } maven { url 'https://repo.spring.io/snapshot' } } dependencies { implementation 'org.springframework.boot:spring-boot-starter' compileOnly 'org.projectlombok:lombok' developmentOnly 'org.springframework.boot:spring-boot-devtools' annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' } tasks.named('test') { useJUnitPlatform() } java { modularity.inferModulePath = true } } def modules= [ "remote", "core", "api" ] dependencies { modules.collect { implementation project(it)} }
2. 简化remote模块的依赖配置
编辑remote模块的build.gradle,移除重复的spring-web依赖:
bootRun { enabled = false } bootJar { enabled = false } jar { enabled = true } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' // 移除冗余的 implementation 'org.springframework:spring-web' }
3. 修正module-info.java的模块权限与依赖
编辑remote模块的module-info.java,添加对spring-boot-autoconfigure的依赖,并开放业务包给Spring自动配置模块:
module lendyourstocks.remote.main { requires org.springframework.boot.starter.web; requires org.springframework.boot.autoconfigure; // 开放你的业务包(替换为实际包路径)给Spring自动配置模块,支持反射 opens com.mrv.remote to org.springframework.boot.autoconfigure; // 若其他模块需要调用该模块的类,需导出对应包 exports com.mrv.remote; }
验证修复
完成上述修改后重新构建项目,即可在remote模块中正常注入和使用RestTemplateBuilder。
内容的提问来源于stack exchange,提问作者marcellorvalle
相关产品推荐
相关产品推荐

