In this article, we will see how to create a custom @annotation to intercept the request before it reaches the controller in the Spring boot.
Also, see how to create a response interceptor in spring boot.
An annotation can be assigned to the complete method or a particular parameter of the method (function), thus to create a custom annotation we create a @interface and configure it.
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER}) public @interface RequestInterceptor { }
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 RequestInterceptorHelper extends RequestBodyAdviceAdapter{ @Override public boolean supports(MethodParameter methodParameter, Type targetType, Class> converterType) { return (methodParameter.hasMethodAnnotation(RequestInterceptor.class) || methodParameter.hasParameterAnnotation(RequestInterceptor.class)); } @Override public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException, IOException { String body = IOUtils.toString(inputMessage.getBody(), UTF_8); //Your logic } @Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { // your logic after body read } }
This class will hold all the logic to process the request before it reaches the controller.
The class extends RequestBodyAdviceAdapter which helps us to override the existing methods.
In supports
method we make sure this class executes only when our annotation is placed and in beforeBodyRead
we add all our logic before the body is created and in afterBodyRead
we add all our logic after the body is created.
As per your requirement, you can use any of the methods.