我应该把我的 ThreadLocals 放在一个弹簧注入的单例中吗? [英] Should I put my ThreadLocals in a spring-injected singleton?

查看:18
本文介绍了我应该把我的 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.

在我的 spring DI tomcat web-app 中,如果我只是让 spring 创建一个包含我的 ThreadLocal(s) 的单例对象,然后将该单例注入任何需要它的类,它似乎可以解决这个问题.

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

}

这仍然具有不必通过许多不关心的层传递用户名的好处,因此使方法参数更简单.@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 而不是显式的 ThreadLocals:

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天全站免登陆