SpringBoot:返回响应,统一封装

版本更新

本文为旧版,新版博客进行了优化和完善,链接如下:

接口返回响应,统一封装(ResponseBodyAdvice + Result)(SpringBoot)


说明

接口的返回响应,封装成统一的数据格式,再返回给前端。

返回响应,统一封装实体,数据结构如下。

在这里插入图片描述

代码

package com.example.core.model;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;

/**
 * 返回响应,统一封装实体
 *
 * @param <T> 数据实体泛型
 */
@Getter
@ToString
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Schema(name = "返回响应", description = "返回响应,统一封装实体")
public class Result<T> {

    @Schema(description = "请求是否成功:true 成功,false 失败", example = "true")
    private Boolean success;

    @Schema(description = "用户提示", example = "操作成功!")
    private String userMessage;

    /**
     * 错误码<br>
     * 调用成功时,为 null。<br>
     * 示例:10001
     */
    @Schema(description = "错误码")
    private Integer errorCode;

    /**
     * 错误信息<br>
     * 调用成功时,为 null。<br>
     * 示例:"验证码无效"
     */
    @Schema(description = "错误信息")
    private String errorMessage;

    /**
     * 数据实体(泛型)<br>
     * 当接口没有返回数据时,为 null。
     */
    @Schema(description = "数据实体(泛型)")
    private T data;


    public static <T> Result<T> success() {
        return success(null);
    }


    public static <T> Result<T> success(T data) {
        return new Result<>(true, "操作成功!", null, null, data);
    }


    public static <T> Result<T> fail(String userMessage, Integer errorCode, String errorMessage) {
        return new Result<>(false, userMessage, errorCode, errorMessage, null);
    }

}

接口测试

代码

package com.example.web;

import com.example.core.model.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("result")
@Tag(name = "Result")
public class ResultController {

    @Operation(summary = "查询 Result<String>")
    @Parameter(name = "name", description = "姓名")
    @GetMapping("/string")
    public Result<String> getResultWithString(@Nullable String name) {
        String text = "您好," + name + "!";
        return Result.success(text);
    }

}


接口文档效果

在这里插入图片描述

接口调用效果

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宋冠巡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值