使用RestTemplate消费Spring分页响应报RestResponsePage类不存在错误如何解决
分页接口消费问题解决方案
错误根因
抛出
TypeNotPresentException通常由两个原因导致:
- 自定义
RestResponsePage类的包路径导入错误,运行时classpath中不存在对应类- Kotlin自定义内联
typeReference函数生成匿名ParameterizedTypeReference实例时,泛型类型信息丢失导致类引用解析失败
修复步骤
1. 基础包路径排查
确认RestResponsePage类的实际包路径与代码中导入的com.test.RestResponsePage完全一致,无拼写错误,类已被正确编译到运行时classpath中。
2. 替换泛型类型引用写法
废弃自定义的内联typeReference函数,在调用restTemplate.exchange时显式创建ParameterizedTypeReference实例:
override fun getNamesById(id: String): List<String> { val uri = URIBuilder("$baseUrl/api/names") .setParameter("search", "id==$id") .build() try { val response = restTemplate.exchange( uri, HttpMethod.GET, null, // 直接显式创建ParameterizedTypeReference,不使用封装的inline函数 object : ParameterizedTypeReference<RestResponsePage<String>>() {} ) return response.body?.content ?: emptyList() } catch (ex: HttpServerErrorException) { throw handleServerError(ex) } }
3. 优化RestResponsePage适配Spring 2.5.x反序列化规则
Spring 2.5.x使用的Jackson版本对继承PageImpl的自定义类反序列化校验更严格,补充注解避免兼容性问题:
@JsonIgnoreProperties(ignoreUnknown = true, value = {"pageable", "sort"}) public class RestResponsePage<T> extends PageImpl<T> { private static final long serialVersionUID = 1L; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public RestResponsePage( @JsonProperty("content") List<T> content, @JsonProperty("number") int number, @JsonProperty("size") int size, @JsonProperty("totalElements") Long totalElements) { super(content, PageRequest.of(number, size), totalElements == null ? 0 : totalElements); } public RestResponsePage(List<T> content, Pageable pageable, long total) { super(content, pageable, total); } public RestResponsePage(List<T> content) { super(content); } public RestResponsePage() { super(new ArrayList<>()); } }
轻量替代方案
如果只需要返回结果的content字段,不需要其他分页参数,可以直接定义简单DTO接收响应,避免继承PageImpl带来的兼容性问题:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class NameResponse( val content: List<String> = emptyList() )
调用时直接使用该DTO作为响应类型:
val response = restTemplate.exchange( uri, HttpMethod.GET, null, object : ParameterizedTypeReference<NameResponse>() {} ) return response.body?.content ?: emptyList()
内容的提问来源于stack exchange,提问作者eth4io
相关产品推荐
相关产品推荐

