spring JsonView解决循环对象引用遇到报错

前言: 本周主要时间用来写社区管理的后台,遇到的主要问题就是对于初期对于模块化理解不够深刻。导致自己一个简单的模块被不断的放大。
遇到问题: 问题描述: 依据前台MockApi来进行单元测试,其中返回后台的返回数据包括:县、乡镇、社区、小区
spring JsonView解决循环对象引用遇到报错
文章图片

县:乡镇:社区:小区 均为一对多的关系。 构造返回数据代码:

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解决循环对象引用遇到报错
文章图片

结论:猜想是我在town的community中设置了town吗?
管他呢,删了试试
再报错: spring JsonView解决循环对象引用遇到报错
文章图片

community.village[0]不存在!
打断点测试 spring JsonView解决循环对象引用遇到报错
文章图片

明明有village[0]啊
突然想到JsonView 查看C层代码:
public class GetAllCountyJsonView implements County.TownJsonView, Town.CommunityJsonView, Community.TownJsonView { }

恍然大悟:County->town->community->town->community->town.....
总结: 感谢单元测试,因为有了单元测试才能够在只有后台的情况下排查出自己后台的BUG,同时也对于JsonView加深了理解
版权声明 【spring JsonView解决循环对象引用遇到报错】本文作者:河北工业大学梦云智开发团队 - 郝泽龙

    推荐阅读