springboot通过threadLocal+参数解析器实现保存当前用户登录信息
在Spring Boot中,可以使用ThreadLocal
来保存当前用户的登录信息,并结合参数解析器(例如拦截器)来自动设置用户信息。以下是一个简化的例子:
- 创建一个自定义的ThreadLocal类来保存用户信息:
public class UserContextHolder {
private static final ThreadLocal<User> userHolder = new ThreadLocal<>();
public static void setUser(User user) {
userHolder.set(user);
}
public static User getUser() {
return userHolder.get();
}
public static void clear() {
userHolder.remove();
}
}
- 创建一个拦截器来在请求处理之前设置用户信息:
@Component
public class UserInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService; // 用于获取用户信息的服务
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String username = request.getHeader("X-Auth-Username"); // 假设用户名在请求头中
User user = userService.getUserByUsername(username); // 从数据库或缓存中获取用户信息
UserContextHolder.setUser(user);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
UserContextHolder.clear(); // 清除线程局部变量
}
}
- 注册拦截器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private UserInterceptor userInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userInterceptor);
}
}
- 使用
UserContextHolder
获取当前用户信息:
public class SomeService {
public void someMethod() {
User user = UserContextHolder.getUser();
// 使用user做后续操作
}
}
确保在请求处理完毕后,在afterCompletion
方法中清除ThreadLocal
存储的用户信息,以避免内存泄漏。
评论已关闭