在spring boot中,为了随时都能取到当前请求的request对象,可以通过RequestContextHolder的静态方法getRequestAttributes()获取Request相关的变量,如request, response等。如下:
public static HttpServletRequest getRequest() {
return
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
是什么原因,可以让我们随时都能取出request或者response对象呢,猜测是存在ThreadLocal:本地线程变量,存储在这个里面的数据可以在整个线程期都可见,线程一旦执行完成就回收,具体源码如下:
public abstract class RequestContextHolder {
private static final boolean jsfPresent =
ClassUtils.isPresent("javax.faces.context.FacesContext", RequestContextHolder.class.getClassLoader());
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<RequestAttributes>("Request attributes");
private static final ThreadLocal<RequestAt