升级Spring Boot 3.2.1后RestTemplate创建失败:缺失KMappedMarker类
解决Spring Boot 3.2.1中RestTemplateBuilder实例化时的Kotlin类缺失问题
错误现象
升级至spring-boot-starter-parent 3.2.1后,使用RestTemplateBuilder创建RestTemplate时抛出以下错误:
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.client.RestTemplate]: Factory method 'restTemplate' threw exception with message: kotlin/jvm/internal/markers/KMappedMarker at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:177) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651) ~[spring-beans-6.1.2.jar:6.1.2] ... 52 common frames omitted Caused by: java.lang.NoClassDefFoundError: kotlin/jvm/internal/markers/KMappedMarker
实例化代码如下:
@Configuration public class BeansFactory { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
直接通过new RestTemplate()可以正常运行,但使用RestTemplateBuilder则报错。
解决方案
在pom.xml的<dependencies>节点中添加Kotlin标准库依赖:
<dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <scope>runtime</scope> </dependency>
添加后执行mvn clean install,重新启动应用即可恢复RestTemplateBuilder的正常使用。
原因说明
Spring Boot 3.2.x版本对RestTemplateBuilder的内部实现进行了调整,部分逻辑依赖了Kotlin语言的KMappedMarker标记接口,该接口属于Kotlin标准库。纯Java项目默认不会引入Kotlin相关依赖,因此会触发NoClassDefFoundError。直接实例化RestTemplate不会经过RestTemplateBuilder的依赖链路,所以不会出现该问题。
内容的提问来源于stack exchange,提问作者vinlos
相关产品推荐
相关产品推荐

