为什么ThreadLocal实用程序总是在Spring MVC应用程序中返回null? [英] Why does ThreadLocal utility always return null in Spring MVC app?
本文介绍了为什么ThreadLocal实用程序总是在Spring MVC应用程序中返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了这个实用程序类来保存Spring MVC应用程序中的临时数据:
I wrote this utility class to save temporary data in a Spring MVC app:
public abstract class FooUtil {
private static final ThreadLocal<String> threadFoo = new ThreadLocal<String>();
public static String getFooId(){
return threadFoo.get();
}
public static void setFooId(String fooId){
threadFoo.set(fooId);
}
public static void removeFooId(){
threadFoo.remove();
}
}
所以我打电话给 FooUtil.setFooId(foo)
。
但是当我稍后调用 FooUtil.getFooId()时/ code>,它总是返回
null
。
我需要一个构造函数吗?或者这不应该是一个抽象类?我不知道。
Do I need a constructor? Or maybe this shouldn't be an abstract class? I don't know.
推荐答案
您需要从与setFooId相同的线程调用getFooId。这样你就可以得到相同的结果。
我会在设置时记录线程名称并获取值以查看它们是否相同。
You need to call getFooId from the same thread as setFooId. This way you get the same result. I would log the thread name when you set and get values to see if they are the same.
这篇关于为什么ThreadLocal实用程序总是在Spring MVC应用程序中返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文