Should I put my ThreadLocals in a spring-injected singleton?

后端 未结 4 1082
庸人自扰
庸人自扰 2020-12-13 07:26

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 08:04

    If you use Spring, you can simply use a request-scoped bean instead of explicit ThreadLocals:

    public interface UserName {
        ...
    }
    
    @Component 
    @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
    public class UsernameImpl implements UserName { 
        private String username; 
        ...
    }
    

提交回复
热议问题