統一controller返回物件

做时间的好朋友發表於2024-04-12

統一controller返回物件

package com.xxx.jscaffold.handler;


import com.xxx.jscaffold.api.dto.common.Result;
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.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = "com.xxx.jscaffold.controller")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 如果不需要進行封裝的,可以新增一些校驗手段,比如新增標記排除的註解
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        // 提供一定的靈活度,如果body已經被包裝了,就不進行包裝
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}

這樣不管controller返回什麼物件,都會被封裝到Result物件裡

相關文章