Feign使用JPA分页类Page和Pageable抛出序列化异常

一、异常如下
feign.AsyncResponseHandler.decode(AsyncResponseHandler.java:119) Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.domain.Page` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (ByteArrayInputStream); line: 1, column: 40] (through reference chain: com.emily.framework.common.base.BaseResponse["data"])

解决这个异常很简单,只需配置如下配置就可以解决:

# feign相关配置
feign:
  # Feign org.springframework.data.domain.Page编码和解码
  # Feign org.springframework.data.domain.Sort编码解码
  autoconfiguration:
    jackson:
      # 如果为true,则将提供PageJacksonModule、SortJacksonModule用jackson对Page进行编码和解码操作,默认:false
      enabled: true
二、org.springframework.cloud.openfeign.FeignAutoConfiguration.FeignJacksonConfiguration自动化配置类
	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass({ Module.class, Page.class, Sort.class })
	@ConditionalOnProperty(value = "feign.autoconfiguration.jackson.enabled", havingValue = "true")
	protected static class FeignJacksonConfiguration {

		@Bean
		@ConditionalOnMissingBean(PageJacksonModule.class)
		public PageJacksonModule pageJacksonModule() {
			return new PageJacksonModule();
		}

		@Bean
		@ConditionalOnMissingBean(SortJacksonModule.class)
		public SortJacksonModule sortModule() {
			return new SortJacksonModule();
		}

	}

开启feign.autoconfiguration.jackson.enabled配置就可以向容器中注入PageJacksonModule、SortJacksonModule两个对JPA分页类的序列化和反序列化操作能力;

三、org.springframework.data.domain.Pageable、org.springframework.data.domain.Page两个分页实现类是在JPA相关实现的pom包中,具体是在如下包:
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.4.6</version>
        </dependency>

Page类的序列化结果是这样的:

        "content": [
            {
                "name": "emily",
                "weight": "10"
            }
        ],
        "number": 1,
        "size": 3,
        "totalElements": 10,
        "numberOfElements": 10,
        "first": false,
        "last": false,
        "totalPages": 4,
        "hasContent": true,
        "pageable": {
            "sort": [],
            "offset": 3,
            "pageNumber": 1,
            "pageSize": 3,
            "paged": true,
            "unpaged": false
        },
        "empty": false
    }

这样的返回结果对于底层库来说是很有帮助的,但是在实际的开发过程中感觉用处不大,无用的字段太多了;

GitHub地址:https://github.com/mingyang66/spring-parent

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页