ThreadLocal是什么?
public T get()
public void set(T value)
public void remove()
1、创建用户上下文实体类
import com.qianxiao.blog.dataobject.UserDO;
public class UserContext {
// 构造方法私有化
private UserContext(){};
private static final ThreadLocal<UserDO> context = new ThreadLocal<>();
/**
* 存放用户信息
* @param userDO
*/
public static void set(UserDO userDO){
context.set(userDO);
}
/**
* 获取用户信息
* @return
*/
public static UserDO get(){
return context.get();
}
/**
* 清除当前线程内引用,防止内存泄漏
*/
public static void remove(){
context.remove();
}
}
2、拦截器中设置用户信息
UserContext.set(userDO);
3、controller中获取用户信息
System.out.println("userData = " + UserContext.get());