我应该将我的ThreadLocals放在弹簧注入的单身吗? [英] Should I put my ThreadLocals in a spring-injected singleton?

查看:113
本文介绍了我应该将我的ThreadLocals放在弹簧注入的单身吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个人(例如在服务器端 http://www.theserverside.com/ news / thread.tss?thread_id = 41473 )建议使用ThreadLocal对象与使用全局变量一样糟糕。
我想象,如果你使它们成为公共静态变量,这是真的。
然后问题是可以很容易地知道它在哪里被使用,改变的地方等等。

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.

在我的春天DI tomcat网络应用程序中,如果我刚刚开始创建一个具有我的ThreadLocal的单例对象,然后将该单例注入任何需要它的类,似乎可以解决这个问题。

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);
    }
}

可能需要的类似如下: / p>

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());
        ...
     }

}

这仍然具有不必通过不需要的许多层传递用户名的优点,因此保持方法参数更简单。
@Autowired是这个类使用该变量的声明。

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?

推荐答案

如果您使用Spring,您可以简单地使用请求范围的bean,而不是明确的 ThreadLocal

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; 
    ...
}

这篇关于我应该将我的ThreadLocals放在弹簧注入的单身吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆