• springboot整合返回数据统一封装


    1、MagCode,错误码枚举类

    1. package com.mgx.common.enums;
    2. import lombok.*;
    3. import lombok.extern.slf4j.Slf4j;
    4. /**
    5. * 错误码
    6. * @author mgx
    7. */
    8. @Slf4j
    9. @NoArgsConstructor
    10. @AllArgsConstructor
    11. public enum MsgCode {
    12. /**
    13. * 枚举标识,根据业务类型进行添加
    14. */
    15. Code_200("操作成功",200)
    16. ,Code_400("错误请求", 400)
    17. ,Code_401("未授权", 401)
    18. ,Code_402("权限不足,请联系管理员", 402)
    19. ,Code_403("禁止请求", 403)
    20. ,Code_404("找不到相关内容", 404)
    21. ,Code_408("请求超时", 408)
    22. ,Code_410("该资源已删除", 410)
    23. ,Code_413("请求体过大", 413)
    24. ,Code_414("请求URI过长", 414)
    25. ,Code_415("不支持的媒体类型", 415)
    26. ,Code_500("系统错误", 500)
    27. ,Code_501("用户未登录", 501)
    28. ,Code_502("错误网关", 502)
    29. ,Code_503("服务不可用", 503)
    30. ,Code_504("网关超时", 504)
    31. ,Code_505("HTTP版本暂不支持", 505)
    32. ,Code_506("时间格式错误", 506)
    33. //自定义提示
    34. ,Code_2001("参数错误", 2001)
    35. ,Code_2002("传入参数不符合条件", 2002)
    36. ,Code_2003("缺少请求参数", 2003)
    37. ,Code_2004("请求方式错误", 2004)
    38. ,Code_2005("sql语法错误", 2005)
    39. ,Code_2006("数据不存在", 2006)
    40. ,Code_2007("同步失败", 2007)
    41. ,Code_2008("添加失败", 2008)
    42. ,Code_2009("修改失败", 2009)
    43. ,Code_2010("删除失败", 2010)
    44. ,Code_2011("查询失败", 2011)
    45. ,Code_2012("评估失败", 2012)
    46. ,Code_2013("移出黑名单失败",2013)
    47. ,Code_2014("该车辆已在黑名单中",2014)
    48. ,Code_2015("请输入正确的手机号",2015)
    49. ,Code_2016("不支持的编码格式", 2016)
    50. ,Code_2017("不支持的解码格式", 2017)
    51. ,Code_2018("保存失败", 2018)
    52. ;
    53. @Getter
    54. @Setter
    55. private String msg;
    56. @Getter
    57. @Setter
    58. private Integer code;
    59. public static String getMessage(Integer code){
    60. MsgCode msgCode;
    61. try {
    62. msgCode = Enum.valueOf(MsgCode.class, "Code_" + code);
    63. } catch (IllegalArgumentException e) {
    64. log.error("传入枚举code错误!code:{}",code);
    65. return null;
    66. }
    67. return msgCode.getMsg();
    68. }
    69. }

    2、统一返回结果类

    1. package com.mgx.common.dto;
    2. import com.mgx.common.enums.MsgCode;
    3. import lombok.AllArgsConstructor;
    4. import lombok.Getter;
    5. import lombok.NoArgsConstructor;
    6. import lombok.Setter;
    7. import java.io.Serializable;
    8. /**
    9. * @author mgx
    10. */
    11. @AllArgsConstructor
    12. @NoArgsConstructor
    13. public class Result implements Serializable {
    14. private static final long serialVersionUID = 1L;
    15. /** 成功与否 */
    16. @Getter protected boolean success;
    17. /** 结果代码 */
    18. @Getter protected Integer code;
    19. /** 消息 */
    20. @Getter protected String message;
    21. /** 标识(方便接口调试) */
    22. @Getter @Setter
    23. protected String tag;
    24. /** 版本(方便接口调试) */
    25. @Getter @Setter
    26. protected String version;
    27. /** 结果数据 */
    28. @Getter protected T data;
    29. /**
    30. * 不需指定code和message
    31. * @return SuccessBuilder
    32. */
    33. public static SuccessBuilder success() {
    34. return new SuccessBuilder(Boolean.TRUE, MsgCode.Code_200.getCode(), MsgCode.Code_200.getMsg());
    35. }
    36. /**
    37. * 同时指定code和message
    38. * @return FailBuilder
    39. */
    40. public static FailBuilder failure() {
    41. return new FailBuilder(Boolean.FALSE);
    42. }
    43. public static class SuccessBuilder {
    44. protected boolean success;
    45. protected Integer code;
    46. protected String message;
    47. protected String tag = "mgx";
    48. protected String version = "1.0";
    49. protected Object data;
    50. protected SuccessBuilder(boolean success, Integer code, String message) {
    51. this.success = success;
    52. this.code = code;
    53. this.message = message;
    54. }
    55. public SuccessBuilder data(Object data) {
    56. this.data = data;
    57. return this;
    58. }
    59. @SuppressWarnings("unchecked")
    60. public Result build() {
    61. return new Result<>(success, code, message, tag, version, (T) data);
    62. }
    63. }
    64. public static class FailBuilder {
    65. protected boolean success;
    66. protected Integer code;
    67. protected String message;
    68. protected String tag = "mgx";
    69. protected String version = "1.0";
    70. protected Object data;
    71. protected FailBuilder(boolean success) {
    72. this.success = success;
    73. }
    74. public FailBuilder code(Integer code) {
    75. this.code = code;
    76. String message = MsgCode.getMessage(code);
    77. if(message != null){
    78. this.message = message;
    79. }
    80. return this;
    81. }
    82. //如果调用code再调用此message方法,此message方法会覆盖code方法中set的message
    83. public FailBuilder message(String message) {
    84. this.message = message;
    85. return this;
    86. }
    87. public FailBuilder data(Object data) {
    88. this.data = data;
    89. return this;
    90. }
    91. @SuppressWarnings("unchecked")
    92. public Result build() {
    93. return new Result<>(success, code, message, tag, version, (T) data);
    94. }
    95. }
    96. }

    3、BooleanResult封装

    1. package com.mgx.common.dto;
    2. import lombok.Data;
    3. import java.io.Serializable;
    4. /**
    5. * @author mgx
    6. */
    7. @Data
    8. public class BooleanResult implements Serializable {
    9. private Boolean result;
    10. private String reason;
    11. public static BooleanResult success(){
    12. BooleanResult booleanResult = new BooleanResult();
    13. booleanResult.setResult(true);
    14. return booleanResult;
    15. }
    16. public static BooleanResult fail(){
    17. return fail(null);
    18. }
    19. public static BooleanResult fail(String reason){
    20. BooleanResult booleanResult = new BooleanResult();
    21. booleanResult.setResult(false);
    22. booleanResult.setReason(reason);
    23. return booleanResult;
    24. }
    25. }

    4、结构展示

    5、类

    1. package com.mgx.controller;
    2. import com.mgx.common.dto.BooleanResult;
    3. import com.mgx.common.dto.Result;
    4. import com.mgx.service.UnifyService;
    5. import com.mgx.vo.param.SaveInfoUserParam;
    6. import com.mgx.vo.result.InfoUserResult;
    7. import io.swagger.annotations.Api;
    8. import io.swagger.annotations.ApiOperation;
    9. import io.swagger.annotations.ApiParam;
    10. import org.apache.ibatis.annotations.Param;
    11. import org.springframework.web.bind.annotation.*;
    12. import javax.annotation.Resource;
    13. /**
    14. * @author mgx
    15. * @date 2023/9/18 3:36 PM
    16. */
    17. @Api(tags = "springboot整合 统一类型结果集")
    18. @RestController
    19. @RequestMapping("/Unify")
    20. public class UnifyController {
    21. @Resource
    22. private UnifyService unifyService;
    23. @ApiOperation("新增")
    24. @PostMapping("/add")
    25. public Result add(@RequestBody SaveInfoUserParam saveInfoUserParam) {
    26. return Result.success().data(unifyService.add(saveInfoUserParam)).build();
    27. }
    28. @ApiOperation("详情")
    29. @GetMapping("/detail")
    30. public Result detail(@ApiParam("用户信息的ID") @Param("id") Long id) {
    31. return Result.success().data(unifyService.detail(id)).build();
    32. }
    33. @ApiOperation("删除")
    34. @DeleteMapping("/delete")
    35. public Result delete(@ApiParam("用户信息的ID") @Param(value = "id") Long id){
    36. return Result.success().data(unifyService.delete(id)).build();
    37. }
    38. @ApiOperation("更新")
    39. @PutMapping("/update")
    40. public Result update(@RequestBody SaveInfoUserParam saveInfoUserParam){
    41. return Result.success().data(unifyService.update(saveInfoUserParam)).build();
    42. }
    43. }
    1. package com.mgx.service;
    2. import com.mgx.common.dto.BooleanResult;
    3. import com.mgx.vo.param.SaveInfoUserParam;
    4. import com.mgx.vo.result.InfoUserResult;
    5. /**
    6. * @author mgx
    7. * @date 2023/9/18 3:38 PM
    8. */
    9. public interface UnifyService {
    10. BooleanResult add(SaveInfoUserParam saveInfoUserParam);
    11. InfoUserResult detail(Long id);
    12. BooleanResult delete(Long id);
    13. BooleanResult update(SaveInfoUserParam saveInfoUserParam);
    14. }
    1. package com.mgx.service.impl;
    2. import com.mgx.common.dto.BooleanResult;
    3. import com.mgx.entity.InfoUser;
    4. import com.mgx.mapper.InfoUserMapper;
    5. import com.mgx.service.UnifyService;
    6. import com.mgx.utils.BeanUtil;
    7. import com.mgx.vo.param.SaveInfoUserParam;
    8. import com.mgx.vo.result.InfoUserResult;
    9. import org.springframework.stereotype.Service;
    10. import javax.annotation.Resource;
    11. import java.util.Objects;
    12. /**
    13. * @author mgx
    14. * @date 2023/9/18 3:38 PM
    15. */
    16. @Service
    17. public class UnifyServiceImpl implements UnifyService {
    18. @Resource
    19. private InfoUserMapper infoUserMapper;
    20. @Override
    21. public BooleanResult add(SaveInfoUserParam saveInfoUserParam) {
    22. InfoUser infoUser = BeanUtil.map(saveInfoUserParam,InfoUser.class);
    23. int addRow = infoUserMapper.insert(infoUser);
    24. if (addRow < 1){
    25. return BooleanResult.fail();
    26. }
    27. return BooleanResult.success();
    28. }
    29. @Override
    30. public InfoUserResult detail(Long id) {
    31. InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);
    32. if (Objects.isNull(infoUser)){
    33. throw new RuntimeException("数据不存在");
    34. }
    35. return BeanUtil.map(infoUser,InfoUserResult.class);
    36. }
    37. @Override
    38. public BooleanResult delete(Long id) {
    39. InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);
    40. if (Objects.isNull(infoUser)){
    41. throw new RuntimeException("数据不存在");
    42. }
    43. int deleteRow = infoUserMapper.deleteByPrimaryKey(id);
    44. if (deleteRow<1){
    45. return BooleanResult.fail();
    46. }
    47. return BooleanResult.success();
    48. }
    49. @Override
    50. public BooleanResult update(SaveInfoUserParam saveInfoUserParam) {
    51. InfoUser queryInfoUser = infoUserMapper.selectByPrimaryKey(saveInfoUserParam.getId());
    52. if (Objects.isNull(queryInfoUser)){
    53. throw new RuntimeException("数据不存在");
    54. }
    55. InfoUser infoUser = BeanUtil.map(saveInfoUserParam,InfoUser.class);
    56. int updateRow = infoUserMapper.updateByPrimaryKeySelective(infoUser);
    57. if (updateRow<1){
    58. return BooleanResult.fail();
    59. }
    60. return BooleanResult.success();
    61. }
    62. }
    1. package com.mgx.utils;
    2. import org.apache.commons.collections4.MapUtils;
    3. import org.springframework.beans.BeanUtils;
    4. import org.springframework.beans.BeansException;
    5. import java.beans.BeanInfo;
    6. import java.beans.Introspector;
    7. import java.beans.PropertyDescriptor;
    8. import java.lang.reflect.Method;
    9. import java.util.*;
    10. /**
    11. * @author mgx
    12. */
    13. public class BeanUtil {
    14. public BeanUtil() {}
    15. public static T map(Object source, Class target) {
    16. if (null == source) {
    17. return null;
    18. } else {
    19. T t = BeanUtils.instantiateClass(target);
    20. BeanUtils.copyProperties(source, t);
    21. return t;
    22. }
    23. }
    24. public static List mapList(Collection sourceList, Class target) {
    25. if (sourceList == null) {
    26. return null;
    27. } else {
    28. List destinationList = new ArrayList<>();
    29. for (Object sourceObject : sourceList) {
    30. T newObj = map(sourceObject, target);
    31. destinationList.add(newObj);
    32. }
    33. return destinationList;
    34. }
    35. }
    36. public static void copyProperties(Object source, Object target, String... ignoreProperties) {
    37. if (null != source && null != target) {
    38. BeanUtils.copyProperties(source, target, ignoreProperties);
    39. }
    40. }
    41. public static T convert(Object source, Class targetClass) {
    42. if (source == null) {
    43. return null;
    44. } else {
    45. try {
    46. T result = targetClass.newInstance();
    47. copyProperties(source, result);
    48. return result;
    49. } catch (IllegalAccessException | BeansException | InstantiationException var3) {
    50. throw new RuntimeException(var3);
    51. }
    52. }
    53. }
    54. public static void copyProperties(Object source, Object target) throws BeansException {
    55. BeanUtils.copyProperties(source, target);
    56. if (target instanceof ConversionCustomizble) {
    57. ((ConversionCustomizble) target).convertOthers(source);
    58. }
    59. }
    60. public interface ConversionCustomizble {
    61. void convertOthers(Object var1);
    62. }
    63. public static Map beanToMap(Object beanObj) {
    64. if (Objects.isNull(beanObj)) {
    65. return null;
    66. }
    67. Map map = new HashMap<>();
    68. try {
    69. BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
    70. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    71. for (PropertyDescriptor property : propertyDescriptors) {
    72. String key = property.getName();
    73. if (key.compareToIgnoreCase("class") == 0) {
    74. continue;
    75. }
    76. Method getter = property.getReadMethod();
    77. Object value = Objects.isNull(getter) ? null : getter.invoke(beanObj);
    78. map.put(key, value);
    79. }
    80. return map;
    81. } catch (Exception ex) {
    82. throw new RuntimeException(ex);
    83. }
    84. }
    85. public static T mapToBean(Map map, Class beanClass) {
    86. if (MapUtils.isEmpty(map)) {
    87. return null;
    88. }
    89. try {
    90. T t = beanClass.newInstance();
    91. BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());
    92. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    93. for (PropertyDescriptor property : propertyDescriptors) {
    94. Method setter = property.getWriteMethod();
    95. if (Objects.nonNull(setter)) {
    96. setter.invoke(t, map.get(property.getName()));
    97. }
    98. }
    99. return t;
    100. } catch (Exception ex) {
    101. throw new RuntimeException(ex);
    102. }
    103. }
    104. }

    6、测试

  • 相关阅读:
    Vue + Ant Design form表单的一些坑
    SpringBoot之@ConfigurationProperties和@Value用法详解
    前台自动化测试:基于敏捷测试驱动开发(TDD)的自动化测试原理
    基于SSM的校园预点餐网站
    分类预测 | MATLAB实现基于Isomap降维算法与改进蜜獾算法IHBA的Adaboost-SVM集成多输入分类预测
    Mac Catalina安装配置hadoop hive hbase
    解密Java多线程中的锁机制:CAS与Synchronized的工作原理及优化策略
    一天的忙碌,一路的飞翔,我的回家之旅
    (第六天)初识Spring框架-SSM框架的学习与应用(Spring + Spring MVC + MyBatis)-Java EE企业级应用开发学习记录
    .Net6 已知问题总结
  • 原文地址:https://blog.csdn.net/qq_42405688/article/details/132986351