threejeez
threejeez

Reputation: 2324

Spring 3 Interceptor Order

I have a Spring 3 Web App that implements two interceptors. Im using a config class annotated @Configuration. The code is as follows:

    @Override
public void addInterceptors(InterceptorRegistry registry) {
    // TODO Auto-generated method stub
    super.addInterceptors(registry);
    registry.addInterceptor(homeInterceptor()).addPathPatterns("/");
    registry.addInterceptor(allInterceptor());
}

No matter what order I add the interceptors to the registry, the allInterceptor's preHandle function is always called before the homeInterceptor's preHandle. Does anyone know how to control the order that interceptors are invoked?

Thanks!

Upvotes: 8

Views: 13017

Answers (2)

Athaphian
Athaphian

Reputation: 139

It seems in Spring 3 they have removed the logic that executes the global interceptors first. Now the interceptors are executed in the order in which they are declared.

Note however that the postHandle of the interceptors is executed in REVERSE order!

Upvotes: 3

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

I looked at the underlying implementation, the global interceptors(not associated to any path mapping) get executed before the mapped interceptors (with associated path patterns). So if you want the homeInterceptor to be executed before the allInterceptor, the allInterceptor may have to be made a mapped interceptor(by providing a path pattern).

These are the two methods that record the interceptors and find the interceptors at runtime: org.springframework.web.servlet.handler.AbstractHandlerMapping.initInterceptors()

org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandlerExecutionChain(Object, HttpServletRequest)

Upvotes: 7

Related Questions