springboot全局统一结果处理

@RestControllerAdvice(basePackages = "com.paic.property.cfom")
@ConditionalOnProperty(name = "global.result.handle.config.enable", havingValue = "true")
@Order(50)
public class GlobalResultHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {

        return true;
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果ContentType不包含JSON则添加
        if(!selectedContentType.includes(MediaType.APPLICATION_JSON)){
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        }
        Class returnValueType = this.getReturnValueType(body, returnType);

        // 返回类型是String
        if(String.class == returnValueType){
            return JSON.toJSONString(DefaultJsonResult.success(body));
        }

        // 返回值是否是JsonResult的子类
        if(JsonResult.class.isAssignableFrom(returnValueType)){
            if(body != null){
                return body;
            }else{
                return DefaultJsonResult.success(null);
            }
        }

        return DefaultJsonResult.success(body);
    }

    /**
     * 获取返回值类型
     * @param value 返回值
     * @param returnType 请求类型
     * @return Class
     */
    private Class getReturnValueType(@Nullable Object value, MethodParameter returnType) {
        // 参考 AbstractMessageConverterMethodProcessor
        return (value != null ? value.getClass() : returnType.getParameterType());
    }

}
 

                            
                        
                    
                    
                    

你可能感兴趣的:(springboot全局统一结果处理)