Spring HandlerInterceptors如何实例化? [英] How are Spring HandlerInterceptors instantiated?
问题描述
每个请求是否都有Spring HandlerInterceptors的新实例?
Is there a new instance of Spring HandlerInterceptors for each request?
我在Spring中有一个拦截器,其中有一个类字段.
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?)
推荐答案
拦截器的实例化方式取决于将其配置为Bean的方式.如果您没有为bean明确指定范围,那么它将像其他任何bean一样成为单例,因此state
字段将由所有请求共享.
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.
如果您确实需要有状态的拦截器,并且不想在请求之间共享状态,请使用ar
if you really need a stateful interceptor and you don't want to share the state between requests, then use a request-scoped bean.
这篇关于Spring HandlerInterceptors如何实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!