spring-mvc - Spring RequestBodyAdvice 没有被触发

标签 spring-mvc

我声明了 @ControllerAdvice实现 RequestBodyAdvice .我的问题是它没有被触发。我有一个 ResponseBodyAdvice在同一个包中,它按预期工作。

@RestControllerAdvice
public class RestPreProcessingAdvice implements RequestBodyAdvice {

  @Override
  public boolean supports(final MethodParameter methodParameter, final Type targetType,
      final Class<? extends HttpMessageConverter<?>> converterType) {
    return checkIfElegiable(...);
  }

  @Override
  public Object handleEmptyBody(final Object body, final HttpInputMessage inputMessage, final MethodParameter parameter,
      final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) {
    return body;
  }

  @Override
  public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, final MethodParameter parameter,
      final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
    return doSomeProcessing(...);
  }

  @Override
  public Object afterBodyRead(final Object body, final HttpInputMessage inputMessage, final MethodParameter parameter,
      final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) {
    return body;
  }
}

我调试并看到这个 @ControllerAdvice正在 ControllerAdviceBean.findAnnotatedBeans() 中找到.但是为什么它没有被触发我到目前为止还没有找到。

我想其他一些人也有类似的问题。
How to use RequestBodyAdviceSpring RequestBodyAdvice is not picking up by the mock MVC frame work, how ever it is working for ResponseBodyAdvice .

最佳答案

在您的 Controller 方法中,尝试使用 @RequestBody 注释方法参数.

例如。

@RestController
public class MyController{

   @RequestMapping(.......)
   public MyResponse greetings(@RequestBody MyRequest requestObject){
        //implementation
   }

}
RequestResponseBodyMethodProcessor类(及其基类 AbstractMessageConverterMethodArgumentResolver)负责调用 beforeBodyRead 的各种抽象方法( afterBodyReadRequestBodyAdvice 等) . RequestMappingHandlerAdapter会选择RequestResponseBodyMethodProcessor仅当 Controller 方法的参数为 时才处理请求注释 @RequestBody .我们可以在 supportsParameter 中看到这个逻辑的实现。 RequestResponseBodyMethodProcessor的方法.

我认为另一种方法是创建我们自己的 MethodProcessor通过扩展 RequestResponseBodyMethodProcessor并覆盖其 supportsParameter方法来放我们自己的逻辑。不过,我还没有测试过。

关于spring-mvc - Spring RequestBodyAdvice 没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41692669/

相关文章:

java - Spring MVC 3 localeChangeInterceptor

java - Spring Boot 禁用/错误映射

java - 试图让 Spring SecurityConfig 与 Spring MVC 和 JavaConfig 一起工作

java - 小型应用程序是否需要 Hibernate 和 Spring 集成?

java - 如何在旅途中从 Java Spring Controller 的 GUI 下载 CSV 文件?

java - Spring GWT http 请求超时

java - 通过基准测试中的注释加载应用程序上下文

java - Spring REST 中的子资源

java - 一些 Controller 的 Spring mvc 过滤器

java - Spring mvc jackson json 映射器-如何将 unicode 编码应用于 json 响应中的特殊字符