英文:
Which HandlerInterceptorAdapter method should be implemented and used to clear ThreadLocal?
问题
我已经编写了HandlerInterceptorAdapter的实现。它将一些与请求相关的数据放入了ThreadLocal中。因为线程会被重用来处理新的请求,所以在处理请求时必须将放入ThreadLocal的数据清除掉。我应该实现哪个HandlerInterceptorAdapter方法来清除它呢?我看到有两个选项,一个是postHandle,另一个是afterCompletion。我需要确保ThreadLocal中的数据被移除。
英文:
I have written an implementation of HandlerInterceptorAdapter. It is putting some request specific data in a ThreadLocal. Because threads are reused for new requests the data that was put in the ThreadLocal has to be removed when request is handled. Which HandlerInterceptorAdapter method should I implement to clear it? There are two options as I see it, postHandle and afterCompletion. I need that data in the ThreadLocal is guaranteed to be removed.
答案1
得分: 2
使用afterCompletion
。它将在任何结果上被调用
> 在请求处理完成后,即在渲染视图后,回调函数将被调用。它将在处理程序执行的任何结果上被调用,因此允许进行适当的资源清理。
参考
注意
- 如果你打算从
preHandle
中返回false
,那么你应该在preHandle
中清理线程本地存储,因为false
表示你已经处理了响应,因此不会调用postHanlde()
或afterCompletion
。
英文:
Use the afterCompletion
. It will be called on any outcome
> Callback after completion of request processing, that is, after rendering the view. Will be called on any outcome of handler execution, thus allows for proper resource cleanup.
Reference
Note
- If you are going to return
false
from frompreHandle
you should clean up thread local in the pre handle itself becausefalse
means you have handled the response, as a resultpostHanlde()
orafterCompletion
will not be called
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论