Spring Boot过滤返回的数据
考虑这样的场景:对于同一个Model类,在不同的api中需要返回不同的字段。该如何优雅的实现呢?
解决方案
采用JsonView,根据定义自动实现字段的过滤。
具体方法
- 创建一个view类,声明一个summary接口,summary接口继承summary用来演示扩展 - public class View { 
 public interface Summary {}
 public interface Summary2 extends Summary{}
 }
- 在model上使用注解,定义view中需要呈现的列 - public class Article { 
 
 private String id;
 
 private String title;
 private String content;
 // 省略getter setter
 }
- 通常在RESTful API工程中,实体类不是直接返回给调用者,而是做了一层封装,我们同样需要在封装类上加上注解 - public class Result { 
 
 private int status;
 
 private String message;
 
 private Object data;
 //省略getter setter
 }
- 在RestController中的API方法上添加注解,说明返回的JsonView 
 public Result test(){
 Article article = new Article();
 article.setId("123");
 article.setTitle("test");
 article.setContent("hahahatest");
 return ResultGenerator.genSuccessResult(article);
 }
- 如果我们注解使用View.Summary.class ,那么return的内容为 - {"status":200,"message":"SUCCESS","data":{"id":"123"}} - 如果我们注解使用View.Summary2.class,那么return的内容为 - {"status":200,"message":"SUCCESS","data":{"id":"123","title":"test"}} 
END
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LeFer!
 评论
