springboot整合返回数据统一封装

1、MagCode,错误码枚举类

package com.mgx.common.enums;import lombok.*;
import lombok.extern.slf4j.Slf4j;/*** 错误码* @author mgx*/
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public enum MsgCode {/*** 枚举标识,根据业务类型进行添加*/Code_200("操作成功",200),Code_400("错误请求", 400),Code_401("未授权", 401),Code_402("权限不足,请联系管理员", 402),Code_403("禁止请求", 403),Code_404("找不到相关内容", 404),Code_408("请求超时", 408),Code_410("该资源已删除", 410),Code_413("请求体过大", 413),Code_414("请求URI过长", 414),Code_415("不支持的媒体类型", 415),Code_500("系统错误", 500),Code_501("用户未登录", 501),Code_502("错误网关", 502),Code_503("服务不可用", 503),Code_504("网关超时", 504),Code_505("HTTP版本暂不支持", 505),Code_506("时间格式错误", 506)//自定义提示,Code_2001("参数错误", 2001),Code_2002("传入参数不符合条件", 2002),Code_2003("缺少请求参数", 2003),Code_2004("请求方式错误", 2004),Code_2005("sql语法错误", 2005),Code_2006("数据不存在", 2006),Code_2007("同步失败", 2007),Code_2008("添加失败", 2008),Code_2009("修改失败", 2009),Code_2010("删除失败", 2010),Code_2011("查询失败", 2011),Code_2012("评估失败", 2012),Code_2013("移出黑名单失败",2013),Code_2014("该车辆已在黑名单中",2014),Code_2015("请输入正确的手机号",2015),Code_2016("不支持的编码格式", 2016),Code_2017("不支持的解码格式", 2017),Code_2018("保存失败", 2018);@Getter@Setterprivate String msg;@Getter@Setterprivate Integer code;public static String getMessage(Integer code){MsgCode msgCode;try {msgCode = Enum.valueOf(MsgCode.class, "Code_" + code);} catch (IllegalArgumentException e) {log.error("传入枚举code错误!code:{}",code);return null;}return msgCode.getMsg();}}

2、统一返回结果类

package com.mgx.common.dto;import com.mgx.common.enums.MsgCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;import java.io.Serializable;/*** @author mgx*/
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {private static final long serialVersionUID = 1L;/** 成功与否 */@Getter protected boolean success;/** 结果代码 */@Getter protected Integer code;/** 消息 */@Getter protected String message;/** 标识(方便接口调试) */@Getter @Setterprotected String tag;/** 版本(方便接口调试) */@Getter @Setterprotected String version;/** 结果数据 */@Getter protected T data;/*** 不需指定code和message* @return SuccessBuilder*/public static SuccessBuilder success() {return new SuccessBuilder(Boolean.TRUE, MsgCode.Code_200.getCode(), MsgCode.Code_200.getMsg());}/*** 同时指定code和message* @return FailBuilder*/public static FailBuilder failure() {return new FailBuilder(Boolean.FALSE);}public static class SuccessBuilder {protected boolean success;protected Integer code;protected String message;protected String tag = "mgx";protected String version = "1.0";protected Object data;protected SuccessBuilder(boolean success, Integer code, String message) {this.success = success;this.code = code;this.message = message;}public SuccessBuilder data(Object data) {this.data = data;return this;}@SuppressWarnings("unchecked")public <T> Result<T> build() {return new Result<>(success, code, message, tag, version, (T) data);}}public static class FailBuilder {protected boolean success;protected Integer code;protected String message;protected String tag = "mgx";protected String version = "1.0";protected Object data;protected FailBuilder(boolean success) {this.success = success;}public FailBuilder code(Integer code) {this.code = code;String message = MsgCode.getMessage(code);if(message != null){this.message = message;}return this;}//如果调用code再调用此message方法,此message方法会覆盖code方法中set的messagepublic FailBuilder message(String message) {this.message = message;return this;}public FailBuilder data(Object data) {this.data = data;return this;}@SuppressWarnings("unchecked")public <T> Result<T> build() {return new Result<>(success, code, message, tag, version, (T) data);}}}

3、BooleanResult封装

package com.mgx.common.dto;import lombok.Data;import java.io.Serializable;/*** @author mgx*/
@Data
public class BooleanResult implements Serializable {private Boolean result;private String reason;public static BooleanResult success(){BooleanResult booleanResult = new BooleanResult();booleanResult.setResult(true);return booleanResult;}public static BooleanResult fail(){return fail(null);}public static BooleanResult fail(String reason){BooleanResult booleanResult = new BooleanResult();booleanResult.setResult(false);booleanResult.setReason(reason);return booleanResult;}}

4、结构展示

5、类

package com.mgx.controller;import com.mgx.common.dto.BooleanResult;
import com.mgx.common.dto.Result;
import com.mgx.service.UnifyService;
import com.mgx.vo.param.SaveInfoUserParam;
import com.mgx.vo.result.InfoUserResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;/*** @author mgx* @date 2023/9/18 3:36 PM*/
@Api(tags = "springboot整合 统一类型结果集")
@RestController
@RequestMapping("/Unify")
public class UnifyController {@Resourceprivate UnifyService unifyService;@ApiOperation("新增")@PostMapping("/add")public Result<BooleanResult> add(@RequestBody SaveInfoUserParam saveInfoUserParam) {return Result.success().data(unifyService.add(saveInfoUserParam)).build();}@ApiOperation("详情")@GetMapping("/detail")public Result<InfoUserResult> detail(@ApiParam("用户信息的ID") @Param("id") Long id) {return Result.success().data(unifyService.detail(id)).build();}@ApiOperation("删除")@DeleteMapping("/delete")public Result<BooleanResult> delete(@ApiParam("用户信息的ID") @Param(value = "id") Long id){return Result.success().data(unifyService.delete(id)).build();}@ApiOperation("更新")@PutMapping("/update")public Result<BooleanResult> update(@RequestBody SaveInfoUserParam saveInfoUserParam){return Result.success().data(unifyService.update(saveInfoUserParam)).build();}}
package com.mgx.service;import com.mgx.common.dto.BooleanResult;
import com.mgx.vo.param.SaveInfoUserParam;
import com.mgx.vo.result.InfoUserResult;/*** @author mgx* @date 2023/9/18 3:38 PM*/
public interface UnifyService {BooleanResult add(SaveInfoUserParam saveInfoUserParam);InfoUserResult detail(Long id);BooleanResult delete(Long id);BooleanResult update(SaveInfoUserParam saveInfoUserParam);}
package com.mgx.service.impl;import com.mgx.common.dto.BooleanResult;
import com.mgx.entity.InfoUser;
import com.mgx.mapper.InfoUserMapper;
import com.mgx.service.UnifyService;
import com.mgx.utils.BeanUtil;
import com.mgx.vo.param.SaveInfoUserParam;
import com.mgx.vo.result.InfoUserResult;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.Objects;/*** @author mgx* @date 2023/9/18 3:38 PM*/
@Service
public class UnifyServiceImpl implements UnifyService {@Resourceprivate InfoUserMapper infoUserMapper;@Overridepublic BooleanResult add(SaveInfoUserParam saveInfoUserParam) {InfoUser infoUser = BeanUtil.map(saveInfoUserParam,InfoUser.class);int addRow = infoUserMapper.insert(infoUser);if (addRow < 1){return BooleanResult.fail();}return BooleanResult.success();}@Overridepublic InfoUserResult detail(Long id) {InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);if (Objects.isNull(infoUser)){throw new RuntimeException("数据不存在");}return BeanUtil.map(infoUser,InfoUserResult.class);}@Overridepublic BooleanResult delete(Long id) {InfoUser infoUser = infoUserMapper.selectByPrimaryKey(id);if (Objects.isNull(infoUser)){throw new RuntimeException("数据不存在");}int deleteRow = infoUserMapper.deleteByPrimaryKey(id);if (deleteRow<1){return BooleanResult.fail();}return BooleanResult.success();}@Overridepublic BooleanResult update(SaveInfoUserParam saveInfoUserParam) {InfoUser queryInfoUser = infoUserMapper.selectByPrimaryKey(saveInfoUserParam.getId());if (Objects.isNull(queryInfoUser)){throw new RuntimeException("数据不存在");}InfoUser infoUser = BeanUtil.map(saveInfoUserParam,InfoUser.class);int updateRow = infoUserMapper.updateByPrimaryKeySelective(infoUser);if (updateRow<1){return BooleanResult.fail();}return BooleanResult.success();}
}
package com.mgx.utils;import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;/*** @author mgx*/
public class BeanUtil {public BeanUtil() {}public static <T> T map(Object source, Class<T> target) {if (null == source) {return null;} else {T t = BeanUtils.instantiateClass(target);BeanUtils.copyProperties(source, t);return t;}}public static <T> List<T> mapList(Collection<?> sourceList, Class<T> target) {if (sourceList == null) {return null;} else {List<T> destinationList = new ArrayList<>();for (Object sourceObject : sourceList) {T newObj = map(sourceObject, target);destinationList.add(newObj);}return destinationList;}}public static void copyProperties(Object source, Object target, String... ignoreProperties) {if (null != source && null != target) {BeanUtils.copyProperties(source, target, ignoreProperties);}}public static <T> T convert(Object source, Class<T> targetClass) {if (source == null) {return null;} else {try {T result = targetClass.newInstance();copyProperties(source, result);return result;} catch (IllegalAccessException | BeansException | InstantiationException var3) {throw new RuntimeException(var3);}}}public static void copyProperties(Object source, Object target) throws BeansException {BeanUtils.copyProperties(source, target);if (target instanceof ConversionCustomizble) {((ConversionCustomizble) target).convertOthers(source);}}public interface ConversionCustomizble {void convertOthers(Object var1);}public static Map<String, Object> beanToMap(Object beanObj) {if (Objects.isNull(beanObj)) {return null;}Map<String, Object> map = new HashMap<>();try {BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (PropertyDescriptor property : propertyDescriptors) {String key = property.getName();if (key.compareToIgnoreCase("class") == 0) {continue;}Method getter = property.getReadMethod();Object value = Objects.isNull(getter) ? null : getter.invoke(beanObj);map.put(key, value);}return map;} catch (Exception ex) {throw new RuntimeException(ex);}}public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass) {if (MapUtils.isEmpty(map)) {return null;}try {T t = beanClass.newInstance();BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass());PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (PropertyDescriptor property : propertyDescriptors) {Method setter = property.getWriteMethod();if (Objects.nonNull(setter)) {setter.invoke(t, map.get(property.getName()));}}return t;} catch (Exception ex) {throw new RuntimeException(ex);}}}

6、测试

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/84899.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

轻量云服务器租用好在哪

从技术上讲&#xff0c;轻量级云服务器是特化了某一配置的高性价比云服务器的结合。下面&#xff0c;我们将了解轻量级云服务器有什么优 势&#xff0c; 使用物理服务器搭建网站&#xff0c;您需要租用整个服务器&#xff0c;这成本会变得非常昂贵。这对于一些比较简单的使用需…

PostgreSQL 数据库实现公网远程连接

文章目录 前言1. 安装postgreSQL2. 本地连接postgreSQL3. Windows 安装 cpolar4. 配置postgreSQL公网地址5. 公网postgreSQL访问6. 固定连接公网地址7. postgreSQL固定地址连接测试 前言 PostgreSQL是一个功能非常强大的关系型数据库管理系统&#xff08;RDBMS&#xff09;,下…

建议收藏《Verilog代码规范笔记_华为》(附下载)

华为verilog编程规范是坊间流传出来华为内部的资料&#xff0c;其贴合实际工作需要&#xff0c;是非常宝贵的资料&#xff0c;希望大家善存。至于其介绍&#xff0c;在此不再赘述&#xff0c;大家可看下图详细了解&#xff0c;感兴趣的可私信领取《Verilog代码规范笔记_华为》。…

JS【filter过滤器】的用法

在JavaScript中&#xff0c;filter()是一个高阶函数&#xff0c;它是数组(Array)的一部分&#xff0c;可用于创建一个新数组&#xff0c;其中包含通过所提供函数实现的测试的所有元素。 filter()函数的语法如下&#xff1a; let newArray arr.filter(callback(element[, ind…

Spring面试题1:Spring框架的核心功能是什么?Spring框架的好处是什么?

该文章专注于面试,面试只要回答关键点即可,不需要对框架有非常深入的回答,如果你想应付面试,是足够了,抓住关键点 Spring框架的核心功能是什么 Spring框架的核心功能包括: 控制反转(IoC):Spring通过IoC容器管理对象的生命周期和依赖关系。它将对象的创建、组装和管理…

React中的dispatch()

在React中&#xff0c;dispatch函数是Redux提供的一个方法&#xff0c;用于触发store中的action。它是Redux中的一个核心概念&#xff0c;用于将action传递给store&#xff0c;从而触发相应的状态更新。 当我们调用dispatch函数时&#xff0c;它会将action对象作为参数&#x…

IDEA开发工具技巧

1.1 IDEA相关插件 idea插件下载地址&#xff1a;https://plugins.jetbrains.com/ 开发必装插件&#xff1a; &#xff08;1&#xff09; 快速查找api接口 RestfulTool 插件&#xff0c;推荐指数⭐⭐⭐⭐⭐ [RestfulTool搜索插件使用详解](https://blog.csdn.net/weixin_450147…

Spring学习笔记2 Spring的入门程序

Spring学习笔记1 启示录_biubiubiu0706的博客-CSDN博客 Spring官网地址:https://spring.io 进入github往下拉 用maven引入spring-context依赖 写spring的第一个程序 引入下面依赖,好比引入Spring的基本依赖 <dependency><groupId>org.springframework</groupId&…

【力扣】9. 回文数

题目描述 给你一个整数 x &#xff0c;如果 x 是一个回文整数&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 回文数是指正序&#xff08;从左向右&#xff09;和倒序&#xff08;从右向左&#xff09;读都是一样的整数。 例如&#xff0c;121 是回文&am…

医学影像信息(PACS)系统软件源码

PACS系统是PictureArchivingandCommunicationSystems的缩写&#xff0c;与临床信息系统&#xff08;ClinicalInformationSystem,CIS&#xff09;、放射学信息系统(RadiologyInformationSystem,RIS)、医院信息系统(HospitalInformationSystem,HIS)、实验室信息系统&#xff08;L…

CentOS 7 安装Libevent

CentOS 7 安装Libevent 1.下载安装包 新版本是libevent-2.1.12-stable.tar.gz。&#xff08;如果你的系统已经安装了libevent&#xff0c;可以不用安装&#xff09; 官网&#xff1a;http://www.monkey.org/~provos/libevent/ 2.创建目录 # mkdir libevent-stable 3.解压 …

QT之QString的用法介绍

QT之QString的用法介绍 成员函数常见用法 成员函数 1&#xff09;QString &append(const QString &str) 将 str 字符串追加到当前字符串末尾&#xff0c;并返回修改后的 QString 对象的引用。 2&#xff09;QString &prepend(const QString &str) 将 str 字符…

死锁问题及分析

最近写了一个hiredis的连接池&#xff0c;借鉴了HiRedis库封装&#xff0c;加了些日志&#xff0c;发现这个在ReleaseClient函数中构造shared_ptr时&#xff0c;没有指定delete。修改后在项目使用过程中发现执行一段时间后总是是卡死&#xff0c;使用的是boost库中的锁及其条件…

MES管理系统在生产中的应用及智能工厂的构建思路

在当今制造业中&#xff0c;随着信息化技术和智能化的不断发展&#xff0c;MES生产管理系统已成为工厂生产的核心组成部分。MES管理系统不仅能够提高生产效率&#xff0c;还可以优化生产流程&#xff0c;提升产品质量。本文将详细介绍MES管理系统在工厂生产中的应用以及构建智能…

VCS flow学习

VCS VCS 是IC从业者常用软件&#xff0c;该篇文章是一个学习记录&#xff0c;会记录在使用过程中各种概念及options。 VCS Flow VCS Flow 可以分为Two-step Flow和Three-step Flow两类。 两步法 两步法只支持Verilog HDL和SystemVerilog的design&#xff0c;两步法主要包括…

Windows AD 组策略 关闭自动更新

1、创建组策略 2、配置 计算机配置 → 策略 → 管理模板 → Windows 组件 → Windows 更新 &#xff08;1&#xff09;禁止 配置自动更新 &#xff08;2&#xff09;启用 "删除使用所有Windows更新功能的访问权限" 3、客户机 更新组策略

Webpack打包时Bable解决浏览器兼容问题

当我们使用js新特性语法编写代码时&#xff0c;在旧的浏览器中兼容性并不好。但是我们希望能够在旧浏览器中使用这些新特性。 使用babel可以使js新代码转换为js旧代码&#xff0c;增加浏览器的兼容性。 如果我们希望在Webpack中支持babel&#xff0c;则需要在Webpack中引入bab…

MySQL 学习笔记(基础)

首先解释数据库DataBase&#xff08;DB&#xff09;&#xff1a;即存储数据的仓库&#xff0c;数据经过有组织的存储 数据库管理系统DataBase Management System&#xff08;DBMS&#xff09;&#xff1a;管理数据库的软件 SQL&#xff08;Structured Query Language&#xf…

Linux 文件权限基础:文件和目录权限管理指南

文章目录 Linux 文件权限基础1. 引言1.1 什么是文件权限1.2 文件权限的重要性 2. Linux 文件权限基础2.1 Linux 文件系统简介2.2 文件和目录的属性2.3 权限类型&#xff1a;读、写和执行2.4 所有者、组和其他用户2.5 权限符号表示法&#xff1a;r、w、x 和 -2.6 使用 ls -l 命令…

47个Docker常见故障的原因和解决方式

本文针对Docker容器部署、维护过程中&#xff0c;产生的问题和故障&#xff0c;做出有针对性的说明和解决方案&#xff0c;希望可以帮助到大家去快速定位和解决类似问题故障。 Docker是一种相对使用较简单的容器&#xff0c;我们可以通过以下几种方式获取信息&#xff1a; 1、…