Java 如果没有HTTP正文,如何使用@ControllerAdvice?

Java 如果没有HTTP正文,如何使用@ControllerAdvice?,java,spring,spring-boot,spring-mvc,controller-advice,Java,Spring,Spring Boot,Spring Mvc,Controller Advice,我想要一个@ControllerAdvice,它是为所有控制器上的所有HTTP请求调用的。不幸的是,它只在请求中有HTTP主体时触发。如果没有,它将被完全忽略。在这种情况下,spring不应该调用handleEmptyBody() 编辑 所有控制器都用@RestController注释 有什么想法吗 @ControllerAdvice public class CatchAllRequestsAdvice implements RequestBodyAdvice { private s

我想要一个
@ControllerAdvice
,它是为所有控制器上的所有HTTP请求调用的。不幸的是,它只在请求中有HTTP主体时触发。如果没有,它将被完全忽略。在这种情况下,spring不应该调用
handleEmptyBody()

编辑 所有控制器都用
@RestController
注释

有什么想法吗

@ControllerAdvice
public class CatchAllRequestsAdvice implements RequestBodyAdvice {

    private static final Logger LOGGER = LoggerFactory.getLogger(CatchAllRequestsAdvice.class);

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

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

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

    @Override
    public Object handleEmptyBody(
        Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType
    ) {
        LOGGER.info("");
        return body;
    }
}
@ControllerAdvice
公共类CatchAllRequestsDevice实现RequestBodyAdvice{
私有静态最终记录器Logger=LoggerFactory.getLogger(CatchAllRequestsAdvice.class);
@凌驾
公共布尔支持(
MethodParameter方法参数,类型targetType,类>转换器类型
) {
LOGGER.info(“”);
返回true;
}
@凌驾
读取前的公共HttpInputMessage(
HttpInputMessage inputMessage,MethodParameter参数,类型targetType,类>转换器类型
)抛出IOException{
LOGGER.info(“”);
返回输入消息;
}
@凌驾
公共对象后读(
对象主体,HttpInputMessage inputMessage,MethodParameter参数,类型targetType,类>转换器类型
) {
LOGGER.info(“”);
返回体;
}
@凌驾
公共对象handleEmptyBody(
对象主体,HttpInputMessage inputMessage,MethodParameter参数,类型targetType,类>转换器类型
) {
LOGGER.info(“”);
返回体;
}
}

您希望通过此建议实现什么?日志记录。是的,我知道InputStream的问题,它只能读取一次。如果你想在每个请求之前运行,你最好编写一个过滤器,或者使用Spring中已经存在的请求日志过滤器(而不是自己运行)。此外,您的方法仅适用于
@RestControllers
@RequestBody
注释类,而不适用于其他请求(例如不带请求体的常规
@Controller
)。Deinum是对的,您可以使用
OncePerRequestFilter
我们所有的控制器都用
@RestController
注释。所以这个控制器上的所有请求都应该调用通知,对吗?但事实并非如此。只有在有请求主体的情况下才会调用它。