开发者

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?)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜