• Spring的 @ControllerAdvice 之 ResponseBodyAdvice对响应结果进行增强


    Spring的 @ControllerAdvice 之 ResponseBodyAdvice对响应结果进行增强

    1. 使用背景

    对响应结果进行统一结果处理时,有时会出现有的接口未进行封装,为了解决该问题,可使用@ControllerAdvice 注解对响应结果进行aop编程增强。

    2. 使用方法

    package com.banneroa.utils;
    
    import cn.hutool.core.annotation.AnnotationUtil;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.MethodParameter;
    import org.springframework.core.annotation.AnnotationUtils;
    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.stereotype.Component;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
    
    /**
     * @author rjj
     * @date 2023/10/21 - 8:58
     */
    @ControllerAdvice
    public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    
        //对符合条件的响应进行处理
        @Override
        public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
            //查看是否有@ResponseBody注解,存在才进行处理
            if (returnType.getMethodAnnotation(ResponseBody.class) != null
                    || AnnotationUtils.findAnnotation(returnType.getContainingClass(), ResponseBody.class) != null) {
                return true;
            }
            return false;
        }
    
        @Override
        public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    
            if (body instanceof ResponseResult){
                //如果是统一结果类型不处理
                return body;
            }
            //不是统一类型,进行封装
            return ResponseResult.okResult(body);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    3. 结果

    接口示例:
    在这里插入图片描述
    使用@ControllerAdvice 之前:
    在这里插入图片描述
    使用之后:
    在这里插入图片描述

  • 相关阅读:
    个人作品录
    【Python】编码
    蓝桥杯每日一题2023.10.22
    PY32F003F18之输入捕获
    每日一文(第一天)
    Tomcat漏洞
    MySQL 不同隔离级别,都使用了什么锁?
    nginx模块
    使用LiME收集主机物理内存的内容时发生宕机
    Spring第二讲:Spring基础 - Spring和Spring框架组成
  • 原文地址:https://blog.csdn.net/RX1125/article/details/133957436