ThreadLocal只能获取本线程的线程数据,而每个用户访问都会是一个单独的线程
package com.itheima.reggie.config;
/*
*基于ThreadLocal封装工具类,用户保存和获取当前 登录用户id
* */
public class BaseContext {
//可以使用泛型指定参数类型,我需要Long便设置为long类型,看个人需求
private static ThreadLocal<Long> threadLocal=new ThreadLocal();
//自定义set、get方法
public static void setCurrentId(Long id){
//调用ThreadLocal.set()设置需要的参数
threadLocal.set(id);
}
public static Long getCurrentId(){
//调用ThreadLocal.get获取上面设置的参数
return threadLocal.get();
}
}
静态方法可以直接类名.方法名访问,设置需要的数据
BaseContext.setCurrentId(id);
获取设置的数据
BaseContext.getCurrentId()
图文示例,同上代码