title: Should I put my ThreadLocals in a spring-injected singleton?
body: <p>Several people (eg at serverside <a href="http://www.theserverside.com/news/thread.tss?thread_id=41473" rel="noreferrer">http://www.theserverside.com/news/thread.tss?thread_id=41473</a>) suggest that using ThreadLocal objects is as bad as using global variables.
  I imagine this is true if you make them public static variables.
  The problem then is that it can be hard to tell where it is used, where it's changed, etc.</p>
  
  <p>In my spring DI tomcat web-app, it seems to counter this problem if I just get spring to create a singleton object that has my ThreadLocal(s) in it, and then inject that singleton into any class that needs it.</p>
  
  <p>So my singleton looks like this:</p>
  
  <pre><code>@Component
  public class Username {
      private ThreadLocal&lt;String&gt; username;
  
      public Username() {
          username = new ThreadLocal&lt;String&gt;();
      }
  
      public String getUsername()
          return username.get();
      }
  
      public void setUsername(String name) {
          username.set(name);
      }
  }
  </code></pre>
  
  <p>And classes that might need it look like this:</p>
  
  <pre><code>@Service
  public class addEntryTransaction {
  
      @Autowired
      Username username;
  
      public void method() {
          ...
          log("Method called by "+username.getUsername());
          ...
       }
  
  }
  </code></pre>
  
  <p>This still has the benefits of not having to pass a username through many layers that don't care, and therefore keeping the method parameters simpler.
  The @Autowired is a declaration that this class uses that variable.</p>
  
  <p>What are the advantages and disadvantages of this approach?</p>