If you can get current depth from a POJO you can do it with a ThreadLocal variable holding a limit. In a controller, before you return a Category instance set a depth limit on a ThreadLocal integer.
@RequestMapping("/categories")
@ResponseBody
public Category categories() {
Category.limitSubCategoryDepth(2);
return root;
}
In a subcategory getter you check depth limit against current depth of a category, if it's over the limit return null.
You'll need to clean up thread local somehow, perhaps with a spring's 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();
}
If you can't get depth from a POJO, you'll need to either make a tree copy with limited depth or learn how to code a custom Jackson serializer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…