如果可以从POJO中获取当前深度,则可以使用具有限制的ThreadLocal变量来实现。在控制器中,在返回Category实例之前,请对ThreadLocal整数设置深度限制。
@RequestMapping("/categories")@ResponseBodypublic Category categories() { Category.limitSubCategoryDepth(2); return root;}在子类别getter中,您可以根据类别的当前深度检查深度限制,如果超过限制则返回null。
您可能需要以某种方式清理本地线程,也许是使用spring的HandlerInteceptor :: afterCompletition。
private Category parent;private Set<Category> subCategories;public Set<Category> getSubCategories() { Set<Category> result; if (depthLimit.get() == null || getDepth() < depthLimit.get()) { result = subCategories; } else { result = null; } return result;}public int getDepth() { return parent != null? parent.getDepth() + 1 : 0;}private static ThreadLocal<Integer> depthLimit = new ThreadLocal<>();public static void limitSubCategoryDepth(int max) { depthLimit.set(max);}public static void unlimitSubCategory() { depthLimit.remove();}如果您无法从POJO获取深度,则需要制作深度有限的树状副本,或者学习如何编写自定义Jackson序列化器。



