Spring RequestBodyAdvice 没有被触发

use*_*611 5 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我想其他一些人也有类似的问题。请参阅如何使用 RequestBodyAdviceSpring RequestBodyAdvice 没有被模拟 MVC 框架接收,它是如何为 ResponseBodyAdvice 工作的

小智 5

在您的控制器方法中,尝试使用 注释方法参数@RequestBody

例如

@RestController
public class MyController{

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

}
Run Code Online (Sandbox Code Playgroud)

RequestResponseBodyMethodProcessor类(及其基类AbstractMessageConverterMethodArgumentResolver)负责调用 的各种抽象方法(beforeBodyReadafterBodyReadRequestBodyAdvice。仅当控制器方法的参数用注释RequestMappingHandlerAdapter时才会选择RequestResponseBodyMethodProcessor处理请求。我们可以看到这个逻辑在的方法中实现。@RequestBodysupportsParameterRequestResponseBodyMethodProcessor

我认为另一种方法是通过扩展重写它的方法来创建我们自己的 方法来放置我们自己的逻辑。不过,我还没有测试过这一点。MethodProcessor RequestResponseBodyMethodProcessorsupportsParameter


use*_*382 2

您应该能够使用 DelegatingWebMvcConfiguration 来设置 RequestBodyAdvice。

@Configuration
public class WebConfig extends DelegatingWebMvcConfiguration {

    public RequestBodyAdvice myRequestBodyAdvice(){
        return new MyRequestBodyAdvice();
    }


    public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
        RequestMappingHandlerAdapter adapter = 
super.requestMappingHandlerAdapter();
        adapter.setRequestBodyAdvice(Arrays.asList(myRequestBodyAdvice()));
        return adapter;
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅Spring 框架文档中的第 22.16.13 节