前提:工做遇到controller中經過註解的方式注入java
@Resource
private HttpServletRequest request;
咱們都知道spring 默認是單例,當遇到併發的時候線程不安全,可是通過測試它安全的。
綜上,肯定spring確定對它作了處理,所以打開個人探索之路.....
上源碼
public class RequestContextListener implements ServletRequestListener {
private static final String REQUEST_ATTRIBUTES_ATTRIBUTE = RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";
public RequestContextListener() {
}
public void requestInitialized(ServletRequestEvent requestEvent) {
if(!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
throw new IllegalArgumentException("Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
} else {
HttpServletRequest request = (HttpServletRequest)requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());
//放到這裏了,RequestContextHolder下的requestAttributes讓咱們跟進去瞅瞅
RequestContextHolder.setRequestAttributes(attributes);
}
}
----------------------------------------------------------------------------------------------------------------
public abstract class RequestContextHolder { private static final boolean jsfPresent = ClassUtils.isPresent("javax.faces.context.FacesContext", RequestContextHolder.class.getClassLoader()); //原來如此啊,是經過threadLocal去保證的 private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes"); private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context"); public RequestContextHolder() { }