名词解释:本地线程变量
作用:在多线程的情况下可以实现现场线程内的数据的共享
自定义ThreadLocal工具api
package com.jt.thread;
import com.jt.pojo.User;
public class UserThreadLocal {
//1.定义变量
private static ThreadLocal<User> thread = new ThreadLocal<>();
public static void set(User user) { //赋值
thread.set(user);
}
public static User get() { //取值
return thread.get();
}
public static void remove() { //移除
thread.remove();
}
}
可以在controller、service等各层使用此变量
在preHandler层进行赋值
UserThreadLocal.set(user);
在各层都可以取值
User user = UserThreadLocal.get();