You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RestTemplate消费Spring分页响应报RestResponsePage类不存在错误如何解决

分页接口消费问题解决方案

错误根因

抛出TypeNotPresentException通常由两个原因导致:

  1. 自定义RestResponsePage类的包路径导入错误,运行时classpath中不存在对应类
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:54:01