Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the execution order of interceptor in Spring Boot application?

I define an interceptor and register it in a class (annotated with Configuration) which extends WebMvcConfigurerAdapter; however, I also use some third-party libraries which also define some interceptors. I want my interceptor to be the last one in the interceptor execution chain. It seems there is no way to enforce this. How to define the execution order of interceptor in Spring Boot application?

like image 561
Rick Avatar asked Sep 19 '15 08:09

Rick


People also ask

How does spring boot interceptor work?

Spring Interceptor are used to intercept client requests and process them. Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods. One example of this processing can be logging for the request before its passed onto the specific handler method.

What is the difference between postHandle () and afterCompletion ()?

prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed. afterCompletion() – called after the complete request is finished and the view is generated.

How do you call an interceptor in Java?

Use the @AroundInvoke annotation to designate interceptor methods for managed object methods. Only one around-invoke interceptor method per class is allowed. Around-invoke interceptor methods have the following form: @AroundInvoke visibility Object method-name(InvocationContext) throws Exception { ... }

Which interceptor is used in an application when maintenance page?

MaintenanceInterceptor – Intercept the web request, check if the current time is in between the maintenance time, if yes then redirect it to maintenance page.


1 Answers

If we've Multiple Interceptors, Instead of @Order Annotation we can do as below.

@EnableWebMvc
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry
            .addWebRequestInterceptor(new WebRequestInterceptor() {
                //Overrides
            }).order(Ordered.HIGHEST_PRECEDENCE);
        registry
           .addWebRequestInterceptor(new WebRequestInterceptor() {
                //Overrides
            }).order(Ordered.LOWEST_PRECEDENCE);
    }
}
like image 85
Sanjay K S Avatar answered Oct 02 '22 19:10

Sanjay K S