---
title: "ThreadLocal在spring中的使用"
author: "dmwdmc"
date: "2013-06-05T10:16:13Z"
tags: []
categories: ["编程语言"]
slug: "threadlocal-spring"
draft: false
lastmod: "2013-06-04T21:40:15Z"
id: 1882336
url: "https://dmwdmc.iteye.com/blog/1882336"
---

spring mvc中它的核心类是DispatcherServlet，

在处理请求时，我们看到它如果掉用了doService方法里的doDispath方法。


```java
 protected void doService(HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
 ......
      doDispatch(request, response);


......
     }
```


doDispatch 方法中，会去拿RequestContextHolder.getRequestAttributes();

而RequestContextHolder.getRequestAttributes() 方法的实现就是从ThreadLocal中取：

```java
public abstract class RequestContextHolder
{
 private static final ThreadLocal requestAttributesHolder = new ThreadLocal();

  private static final ThreadLocal inheritableRequestAttributesHolder = new InheritableThreadLocal();
  public static RequestAttributes getRequestAttributes()
  {
    RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get();
    if (attributes == null) {
      attributes = (RequestAttributes)inheritableRequestAttributesHolder.get();
    }
    return attributes;
  }

}
```


从而保证的request 里面value的线程安全。