Several people (eg at serverside http://www.theserverside.com/news/thread.tss?thread_id=41473) 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.
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.
So my singleton looks like this:
@Component
public class Username {
private ThreadLocal<String> username;
public Username() {
username = new ThreadLocal<String>();
}
public String getUsername()
return username.get();
}
public void setUsername(String name) {
username.set(name);
}
}
And classes that might need it look like this:
@Service
public class addEntryTransaction {
@Autowired
Username username;
public void method() {
...
log("Method called by "+username.getUsername());
...
}
}
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.
What are the advantages and disadvantages of this approach?