如果你可以從一個POJO獲取當前的深度,你可以用一個ThreadLocal變量保存界限做到這一點。在控制器中,在返回一個Category實例之前,在ThreadLocal整數上設置深度限制。
@RequestMapping("/categories")
@ResponseBody
public Category categories() {
Category.limitSubCategoryDepth(2);
return root;
}
在子類別getter中,您檢查深度限制與類別的當前深度,如果超出限制返回null。
你需要清理線程局部莫名其妙,或許還有一個春天的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得到深度,你需要要麼使樹副本有限的深度或學習如何編寫自定義的串行傑克遜。
我不是真正熟悉您正在使用,但圖書館,也許標誌着子類別,短暫? –