近日,在学习springboot全局异常处理与全局响应对象时,因为项目本身使用了swagger,启用全局响应处理类后,swagger页面无法使用,如下图
全局响应类需集成ResponseBodyAdvice接口,并添加注解@ControllerAdvice和@Component,交由spring进行管理
经排查后,是由于全局响应类中supports方法拦截了请求,在supports方法的返回值前增加过滤判断,是swagger的Docket类则返回false
改动后代码如下:
1 package com.myfather.demo3.exception; 2 3 import com.myfather.demo3.common.AjaxResponse; 4 import org.springframework.core.MethodParameter; 5 import org.springframework.http.HttpStatus; 6 import org.springframework.http.MediaType; 7 import org.springframework.http.server.ServerHttpRequest; 8 import org.springframework.http.server.ServerHttpResponse; 9 import org.springframework.stereotype.Component; 10 import org.springframework.web.bind.annotation.ControllerAdvice; 11 import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; 12 import springfox.documentation.spring.web.plugins.Docket; 13 14 /** 15 * @Description 全局响应类 16 * @Author liangZai 17 * @Date 2020/12/17 22:09 18 * @Version 1.0 19 */ 20 @Component 21 @ControllerAdvice 22 public class GlobalResponseAdvice implements ResponseBodyAdvice { 23 /** 24 * Whether this component supports the given controller method return type 25 * and the selected {@code HttpMessageConverter} type. 26 * 27 * @param returnType the return type 28 * @param converterType the selected converter type 29 * @return {@code true} if {@link #beforeBodyWrite} should be invoked; 30 * {@code false} otherwise 31 */ 32 @Override 33 public boolean supports(MethodParameter returnType, Class converterType) { 34 //默认结果为false,表示支持哪些方法,改为true之后为支持所有方法 35 // return false; 36 return !returnType.getDeclaringClass().equals(Docket.class); 37 // return true; 38 } 39 40 /** 41 * Invoked after an {@code HttpMessageConverter} is selected and just before 42 * its write method is invoked. 43 * 44 * @param body the body to be written 45 * @param returnType the return type of the controller method 46 * @param mediaType the content type selected through content negotiation 47 * @param selectedConverterType the converter type selected to write to the response 48 * @param request the current request 49 * @param response the current response 50 * @return the body that was passed in or a modified (possibly new) instance 51 */ 52 @Override 53 public Object beforeBodyWrite(Object body, 54 MethodParameter returnType, 55 MediaType mediaType, 56 Class selectedConverterType, 57 ServerHttpRequest request, 58 ServerHttpResponse response) { 59 60 if(mediaType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)){ 61 if(body instanceof AjaxResponse){ 62 response.setStatusCode(HttpStatus.valueOf(( 63 (AjaxResponse)body).getCode() 64 )); 65 return body; 66 } 67 else { 68 response.setStatusCode(HttpStatus.OK); 69 return AjaxResponse.success(body); 70 } 71 } 72 return null; 73 } 74 }