权限管理系统 ThreadLocal的使用:在同一线程中获取用户信息

ThreadLocal的使用:在同一线程中获取用户信息

/*****************************************************************************************/

public class ThreadUtils implements Runnable {

private static class ThreadUtilsHolder {

private static final ThreadUtils INSTANCE = new ThreadUtils();

}

private ThreadUtils() {

}

public static final ThreadUtils getInstance() {

return ThreadUtilsHolder.INSTANCE;

}

private User user;

private final ThreadLocal<User> userId = new ThreadLocal<User>() {

@Override

protected User initialValue() {

return user;

}

};

public void setUserId(User user) {

this.user = user;

}

public User getUserId() {

return userId.get();

}

@Override

public void run() {

}

}

/*********************************************************************************************************/

登录时将用户信息保存在ThreadLocal中,并启动线程

ThreadUtils Tutils =  ThreadUtils.getInstance();

Thread thread = new Thread(Tutils);

Tutils.setUserId(loginuser);

thread.start();

在切面中获取线程中的用户信息

ThreadUtils Tutils = ThreadUtils.getInstance();

public User getUser() {

User user = Tutils.getUserId();

return user;

}

猜你喜欢

转载自blog.csdn.net/boke7265/article/details/78187396