SpringBoot接口返回统一格式

package com.example.springboot.common;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Auther: 
 * @Date: 2023/02/24 17:04
 * @Description:
 */
@ControllerAdvice
public class CommonResultAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Result<Object> result=new Result<>();
        result.setCode(200);
        result.setMsg("ok");
        result.setData(body);
        return result;
    }
}

 

posted @ 2023-03-03 14:14  甜菜波波  阅读(33)  评论(0编辑  收藏  举报