在项目中,如果需要使用ThreadLocal,可以编写一个类,举例如下,仅供参考:
public class BaseContext {
public static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void set(String value) {
threadLocal.set(value);
}
public static String get() {
return threadLocal.get();
}
public static void remove() {
threadLocal.remove();
}
}
如果需要存入多个值,可以将泛型改为Map,在set的时候,组装好数据将map存到threadlocal里,同样举个例子,仅供参考
public class BaseMapContext {
public static ThreadLocal<Map<String, String>> threadLocal = new ThreadLocal<>();
public static void set(Map<String, String> map){
threadLocal.set(map);
}
public static String get(String key){
return threadLocal.get().get(key);
}
public static void remove(){
threadLocal.remove();
}
}