Search code examples
springspring-restcontrollerspring-rest

Spring Access @RequestBody object outside Controller Method


I have a component that should be able to access the @RequestBody object that is sent within a request and check if it’s of a certain type.

Is there a way to do this, without deserializing the object again and without manually saving the @RequestBody somewhere when the controller method (where the @RequestBody parameter is declared) is called?

I’d like a solution that works independently of the rest controller and without modifying it’s methods.

Thanks!


Solution

  • Using a class that extends RequestBodyAdviceAdapter, as explained here, solves the problem.

    @ControllerAdvice
    public class CustomRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
        @Override
        public boolean supports(MethodParameter methodParameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
            return true;
        }
    
        @Override
        public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                    Class<? extends HttpMessageConverter<?>> converterType) {
            return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
        }
    
    }
    

    The method supports should return true if the Class should be able to handle the request. And inside afterBodyRead you can access the object and process it.