Example usage for org.springframework.web.servlet.mvc.method.annotation ResponseBodyAdvice beforeBodyWrite

List of usage examples for org.springframework.web.servlet.mvc.method.annotation ResponseBodyAdvice beforeBodyWrite

Introduction

In this page you can find the example usage for org.springframework.web.servlet.mvc.method.annotation ResponseBodyAdvice beforeBodyWrite.

Prototype

@Nullable
T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
        Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
        ServerHttpResponse response);

Source Link

Document

Invoked after an HttpMessageConverter is selected and just before its write method is invoked.

Usage

From source file:org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdviceChain.java

@SuppressWarnings("unchecked")
public <T> T invoke(T body, MethodParameter returnType, MediaType selectedContentType,
        Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
        ServerHttpResponse response) {/*from w w w .java 2 s  .c  om*/

    if (this.advice != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking ResponseBodyAdvice chain for body=" + body);
        }
        for (Object advice : this.advice) {
            if (advice instanceof ControllerAdviceBean) {
                ControllerAdviceBean adviceBean = (ControllerAdviceBean) advice;
                if (!adviceBean.isApplicableToBeanType(returnType.getContainingClass())) {
                    continue;
                }
                advice = adviceBean.resolveBean();
            }
            if (advice instanceof ResponseBodyAdvice) {
                ResponseBodyAdvice<T> typedAdvice = (ResponseBodyAdvice<T>) advice;
                if (typedAdvice.supports(returnType, selectedConverterType)) {
                    body = typedAdvice.beforeBodyWrite(body, returnType, selectedContentType,
                            selectedConverterType, request, response);
                }
            } else {
                throw new IllegalStateException("Expected ResponseBodyAdvice: " + advice);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("After ResponseBodyAdvice chain body=" + body);
        }
    }
    return body;
}