Custom @annotation for Response interception in Spring boot

In this article, we will see how to create a custom annotation for response interception in Java’s Spring Boot.

Also, see how to create a request interceptor in spring boot.

An annotation can be applied to the complete method or any of its parameters and to create a custom annotation we create an @interface that will be implemented and used in a helper class.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
public @interface ResponseInterceptor {
}

Here @Target decides where this annotation can be used and @Retention will decide when it will be applied.

Once the interface is declared we have to create a class that will make use of this interface.

@RestControllerAdvice
public class ResponseInterceptorHandler implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class converterType) {
        return (methodParameter.hasMethodAnnotation(ResponseInterceptor.class) || methodParameter.hasParameterAnnotation(ResponseInterceptor.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter MethodParameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //Your logic
    }
}

This handler class holds all the logic before the response is returned and it overrides the ResponseBodyAdvice that will help us to override the existing methods where we can interceptor the response and make changes if required.

In supports method we make sure this class executes only when our annotation is placed and in beforeBodyWrite we can intercept the response object and process it.