Skip to content
Advertisement

How to make multiple Spring HandlerInterceptors execute in a specific order

I’m currently working on a Spring boot project. I have a dependency on a library project that has an interceptor(LibraryProjectInterceptor.java) and a public class LibraryProjectConfig implements WebMvcConfigurer and overrides the addInterceptors() method to add the LibraryProjectInterceptor to the InterceptorRegistry. In my actual project where I added this library project dependency, I have created an interceptor(ActualProjectInterceptor) that needs to be executed after the LibraryProjectInterceptor has been executed. I have tried adding @Order(value = Ordered.LOWEST_PRECEDENCE) to the ActualProjectInterceptor to make it execute after the LibraryProjectInterceptor but it is not working. Can someone help me

Library Project:

public class LibraryProjectInterceptor implements HandlerInterceptor {
 ......
}




  @Configuration
  @EnableWebMVC
  public class LibraryProjectConfig implements WebMvcConfigurer {
    ......
        @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(LibraryProjectInterceptor);
            }
    ......
    }

Actual Project: pom.xml

 ......

<dependencies>
 <dependency> 
   <groupId>com.example</groupId>
   <artifactId>library-project</artifactId>
   <version>1.0.16</version>
 </dependency>
 ......

@Component
@Order(value = Ordered.LOWEST_PRECEDENCE)
public class ActualProjectInterceptor implements HandlerInterceptor{
.......
}

@SpringBootApplication
public class ActualProjectConfig implements WebMvcConfigurer {
......
    @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(ActualProjectInterceptor);
        }
......
}

Advertisement

Answer

Try this, I hope it will be working.

@Component
public class ActualProjectInterceptor implements HandlerInterceptor {}

@SpringBootApplication
public class ActualProjectConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ActualProjectInterceptor)
                .order(Ordered.LOWEST_PRECEDENCE);
    }
}

addInterceptor() method creates the InterceptorRegistration DSL object which has order() method to specify what you need.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement