Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Spring HandlerInterceptors instantiated?

Is there a new instance of Spring HandlerInterceptors for each request?

I have an interceptor in Spring, which has a class field.

public class MyInterceptor extends HandlerInterceptorAdapter {
    Private boolean state = false;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        state = true;
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if (state == true) {
        System.out.println("Success");
        }
}

If this interceptor is used will it always print "Success"? (No matter how many threads are doing this at the same time?)

like image 719
Nicolai Avatar asked Aug 26 '11 08:08

Nicolai


1 Answers

How the interceptor is instantiated depends how you configiure it as a bean. If you don't explicitly specify a scope for the bean, then it'll be a singleton like any other bean, and so the state field will be shared by all requests.

In this sense, interceptors are no different to controllers - be very careful about putting conversation state in them, since the objects will be shared across requests.

if you really need a stateful interceptor and you don't want to share the state between requests, then use a request-scoped bean.

like image 122
skaffman Avatar answered Oct 10 '22 23:10

skaffman