我声明了 @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 RequestBodyAdvice和 Spring 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
的各种抽象方法( afterBodyRead
、 RequestBodyAdvice
等) . RequestMappingHandlerAdapter
会选择RequestResponseBodyMethodProcessor
仅当 Controller 方法的参数为 时才处理请求注释 与 @RequestBody
.我们可以在 supportsParameter
中看到这个逻辑的实现。 RequestResponseBodyMethodProcessor
的方法.我认为另一种方法是创建我们自己的
MethodProcessor
通过扩展 RequestResponseBodyMethodProcessor
并覆盖其 supportsParameter
方法来放我们自己的逻辑。不过,我还没有测试过。
关于spring-mvc - Spring RequestBodyAdvice 没有被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41692669/