Spring RequestBodyAdvice未被触发

时间:2017-01-17 08:51:39

标签: 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

2 个答案:

答案 0 :(得分:2)

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

E.g。

@RestController
public class MyController{

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

}

RequestResponseBodyMethodProcessor类(及其基类AbstractMessageConverterMethodArgumentResolver)负责调用beforeBodyRead的各种抽象方法(afterBodyReadRequestBodyAdvice等)。仅当控制器方法的论证注释 RequestMappingHandlerAdapter时,RequestResponseBodyMethodProcessor才会选择@RequestBody来处理请求。我们可以在supportsParameter的{​​{1}}方法中看到这种逻辑。

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

答案 1 :(得分:1)

您应该可以使用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;
    }
}

Spring Framework Docs

中的第22.16.13节