Spring MVC 3.2 @ResponseBody interceptor

后端 未结 4 2132
北荒
北荒 2021-02-05 22:28

In our application we are using JSON for request and response. The controller methods are annotated with @RequestBody(). The object being returned e.g. TransferResponse. I would

4条回答
  •  广开言路
    2021-02-05 22:43

    As Pavel Horal already mentioned, when postHandle() method is called, the response body object is already converted to JSON and written to response. You can try to write your own custom annotation and aspect in order to intercept the controller response body objects.

    // custom annotation
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyCustomAnnotation {
    }
    
    // aspect
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.springframework.stereotype.Component;
    
    @Aspect
    @Component
    public class MyCustomAnnotationAspect {
        @Around(value = "@annotation(org.package.MyCustomAnnotation)", argNames = "pjp")
        public Object aroundAdvice(final ProceedingJoinPoint pjp) {
            // this is your response body
            Object responseBody = pjp.proceed();
            return responseBody;
        }
    }
    

    Enable support for AspectJ aspects using @EnableAspectJAutoProxy

提交回复
热议问题