Java项目返回数据封装 + swagger2
1,封装返回数据对象
package com.yw.common.util; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Result<T> { @ApiModelProperty(value = "状态码") private Integer code; @ApiModelProperty(value = "响应信息") private String msg; @ApiModelProperty(value = "数据") private T data; }
这里要使用泛型,不能用Object,否则swagger2配置ui界面无法解读data中的数据
2,ResultUtil.java
package com.yw.common.util; /** * @Author zl * @Description * @Date 2020/11/1 19:55 */ public class ResultUtil { protected enum ResultEnum { SUCCESS(20000, "success"), FAIL(50000, "fail"),; ; private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } } /**成功且带数据**/ public static <T> Result<T> success(T object){ Result<T> result = new Result<T>(); result.setCode(ResultEnum.SUCCESS.getCode()); result.setMsg(ResultEnum.SUCCESS.getMsg()); result.setData(object); return result; } /**成功但不带数据**/ public static <T>Result<T> success(){ return success(null); } /**失败**/ public static <T> Result<T> fail(Integer code, String msg){ Result<T> result = new Result<T>(); result.setCode(code); result.setMsg(msg); return result; } /**失败**/ public static <T> Result<T> fail(){ Result<T> result = new Result<T>(); result.setCode(ResultEnum.SUCCESS.getCode()); result.setMsg(ResultEnum.SUCCESS.getMsg()); return result; } }
3,待返回的封装对象
package com.yw.model.resp.equipment; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @Author zl * @Description * @Data 2020/10/30 14:48 */ @Data public class ComplexityResp { @ApiModelProperty(value = "体系复杂度") private double clusterCoefficient; @ApiModelProperty(value = "网络密度") private double networkDensity; @ApiModelProperty(value = "平均距离") private double averageDistance; @ApiModelProperty(value = "体系复杂度") private double complexityInfluenceDegree; }
4,controller方法 和 swagger2界面
@ApiOperation("返回体系复杂度特性影响度数值") @PostMapping("/complexityInfluenceDegree") public Result<ComplexityResp> complexityInfluenceDegree(@ApiParam("体系复杂度请求数据")@RequestBody(required = false)ComplexityReq complexityData) { return equipmentService.complexityInfluenceDegree(complexityData); }
心有所想,必有回响