ResponseBodyAdvice切面操作返回值

ResponseBodyAdvice可以在注解@ResponseBody将返回值处理成相应格式之前操作返回值。实现这个接口即可完成相应操作。可用于返回值加密

@ControllerAdvice标记类

接口

public interface ResponseBodyAdvice{
  /**
     * Whether this component supports the given controller method return type
     * and the selected {@code HttpMessageConverter} type.(此组件是否支持给定的控制器方法返回值类型)
     * @param returnType the return type(返回类型)
     * @param converterType the selected converter type(选中的转换器类型)
     * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
     * {@code false} otherwise(返回是否调用处理方法)
     */
    boolean support(MethodParameter returnType, Class> converterType);

/**
     * Invoked after an {@code HttpMessageConverter} is selected and just before
     * its write method is invoked.
     * @param body the body to be written(需要写操作的body)
     * @param returnType the return type of the controller method
     * @param selectedContentType the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request the current request
     * @param response the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    @Nullable
    T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
            Class> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response);
}

其它

在参数被方法调用之前截取参数的是RequestBodyAdvice

@ControllerAdvice
public class LogRequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class> aClass) {
        return true;
    }
 
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class> aClass) throws IOException {
        return httpInputMessage;
    }
 
    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class> aClass) {
        Method method=methodParameter.getMethod();
        log.info("{}.{}:{}",method.getDeclaringClass().getSimpleName(),method.getName(),JSON.toJSONString(o));
        return o;
    }
 
    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class> aClass) {
        Method method=methodParameter.getMethod();
        log.info("{}.{}",method.getDeclaringClass().getSimpleName(),method.getName());
        return o;
    }
}

你可能感兴趣的:(ResponseBodyAdvice切面操作返回值)