spring JsonView解决循环对象引用遇到报错
前言:
本周主要时间用来写社区管理的后台,遇到的主要问题就是对于初期对于模块化理解不够深刻。导致自己一个简单的模块被不断的放大。
遇到问题:
问题描述:
依据前台MockApi来进行单元测试,其中返回后台的返回数据包括:县、乡镇、社区、小区
文章图片
县:乡镇:社区:小区 均为一对多的关系。
构造返回数据代码:
public static County getOneCounty() {
logger.debug("构造返回数据县")
County county = new County();
county.setId(new Random().nextLong());
county.setName(new RandomString().nextString());
logger.debug("获取乡镇");
logger.debug("乡镇中有社区List,社区中有小区List")
Town town = TownControllerTest.getOneTown();
county.getTowns().add(town);
return county;
}
测试代码
@Test
void getCounty() throws Exception {
String url = baseUrl + "/county";
County county = getOneCounty();
Mockito.doReturn(county).when(this.systemService).getCounty();
this.mockMvc.perform(MockMvcRequestBuilders.get(url))
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(county.getId()))
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value(county.getName()))
.andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].id").exists())
.andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].communities[0].id").exists())
.andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].communities[0].villages[0].id").exists())
.andExpect(MockMvcResultMatchers.status().isOk());
}
报错
through reference chain: club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]......
解决:
看错误提示 根据报错提示可以看出是一直在town和community循环了:town中包含community,每个community又包含一个town,如此不断的获取。
检查返回数据
![spring JsonView解决循环对象引用遇到报错](https://img.it610.com/image/info9/8cb566704ccc4137b6875731bcbbc9d5.jpg)
文章图片
结论:猜想是我在town的community中设置了town吗?
管他呢,删了试试
再报错:
![spring JsonView解决循环对象引用遇到报错](https://img.it610.com/image/info9/a72b80f1338d45a6aeeb1aada87c9d64.jpg)
文章图片
community.village[0]不存在!
打断点测试
![spring JsonView解决循环对象引用遇到报错](https://img.it610.com/image/info9/5145279dd2d94ce0adef051c535797d9.jpg)
文章图片
明明有village[0]啊
突然想到JsonView 查看C层代码:
public class GetAllCountyJsonView implements
County.TownJsonView,
Town.CommunityJsonView,
Community.TownJsonView { }
恍然大悟:County->town->community->town->community->town.....
总结: 感谢单元测试,因为有了单元测试才能够在只有后台的情况下排查出自己后台的BUG,同时也对于JsonView加深了理解
版权声明 【spring JsonView解决循环对象引用遇到报错】本文作者:河北工业大学梦云智开发团队 - 郝泽龙
推荐阅读
- parallels|parallels desktop 解决网络初始化失败问题
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- Activiti(一)SpringBoot2集成Activiti6
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 2018-07-09|2018-07-09 Spring 的DBCP,c3p0
- Spark|Spark 数据倾斜及其解决方案
- 解决SyntaxError:|解决SyntaxError: invalid syntax
- Spectrum|Spectrum 区块偶尔停止同步问题排查与解决笔记