SpringBoot 集成 spring-boot-starter-wrap 统一返回封装
      
      
    
   
  
  
    项目仓库地址
- 依赖引入后,所有接口返回都会被封装成{code:0,data:{},msg:’’}的形式
 
- 当接口抛出 WrapException,将会封装成{code:-1,msg:’’},且 httpStatus 为 550
 
- 当接口不想被封装时,只需要在方法或类上加@NotWrap 注解即可
 
集成
引入依赖
1 2 3 4 5 6
   |  <dependency>     <groupId>com.seepine</groupId>     <artifactId>spring-boot-starter-wrap</artifactId>     <version>0.2.0</version> </dependency>
 
  | 
 
指定拦截包路径
不指定则默认拦截所有。若有集成 Swagger,必须指定,否则可能导致Unable to infer base url.
1 2 3
   | wrap:      scan-packages: com.example.controller
   | 
 
例子
#1 返回字符串类型
controller:
1 2 3 4
   | @RequestMapping("hello") public String hello(){         return "hello world"; }
  | 
 
response:
需要注意,此时前端接收到的是jsonString,需要转为对象JSON.parse(jsonString)
1 2 3 4
   | {   "code": 0,   "data": "hello world" }
  | 
 
#2 返回对象类型
entity:
1 2 3 4 5 6 7 8 9 10 11
   | class User {     Long id;     String fullName;     Integer age;
      public User(Long id, String fullName, Integer age) {         this.id = id;         this.fullName = fullName;         this.age = age;     } }
  | 
 
controller:
1 2 3 4
   | @RequestMapping("user") public User user(){         return new User(1L,"jackson",24); }
  | 
 
response:
1 2 3 4 5 6 7 8
   | {   "code": 0,   "data": {     "id": 1,     "fullName": "jackson",     "age": 24   } }
  | 
 
#3 带错误信息的异常处理
controller:
1 2 3 4 5 6
   | @RequestMapping("sum") public String sum() throws WrapException{          throw new WrapException("错误信息");     return "sum"; }
  | 
 
response:
1 2 3 4
   | {   "code": -1,   "msg": "错误信息" }
  | 
 
#4 带数据的异常处理
controller:
1 2 3 4 5 6
   | @RequestMapping("del") public String del() throws WrapException{          throw new WrapException(new Object(),"错误信息2");     return "del"; }
  | 
 
response:
1 2 3 4 5 6 7
   | {   "code": -1,   "data": {        },   "msg": "错误信息2" }
  |