关于在Spring Boot + SpringSecurity工程中Sercurity上下文对象无法传递至新线程的问题解决

关于在Spring Boot + SpringSecurity工程中Sercurity上下文对象无法传递至新线程的问题解决

背景

OJ系统后端开发过程中,前端用户提交代码后,后端接收到请求开始对提交记录进行保存并开启一个新线程用于判题,但是由于开启了Mybatis-plus自动填充功能,在保存数据时需要从Sercurity上下文对象中取得UserDetail信息,由于新线程的SercurityConxt中的UserDetail信息为空导致空指针异常。最终通过Security自动传递解决问题

添加线程池Bean

java 复制代码
@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        // 使用 DelegatingSecurityContextExecutorService 包装线程池
        return new DelegatingSecurityContextExecutorService(Executors.newFixedThreadPool(5));
    }
}

添加后通过@Async注解开启的异步线程可在创建时获取到SercurityContext对象。

相关推荐
2601_9615934232 分钟前
Rust 开发环境配置繁琐?RustRover 开箱即用搞定编码调试
开发语言·后端·macos·rust
HZZD_HZZD1 小时前
DL/T 645-2026新国标深度解读与智能电表协议适配实战:从帧结构变化到Java采集器升级的全链路改造方案
java·开发语言
犀利豆3 小时前
AI in Harness(三)
人工智能·后端
IT_陈寒3 小时前
Java的Stream.parallel()把我CPU跑爆了,这种优化要谨慎
前端·人工智能·后端
山登绝顶我为峰 3(^v^)34 小时前
C/C++ 交叉编译方法
java·c语言·c++
一叶飘零_sweeeet4 小时前
Codex 与 Claude Code 深度拆解:两代 AI 编程智能体的技术本质与 Java 实战指南
java·ai·codex·claude code
子兮曰4 小时前
Bun 重写为 Rust:11天、64个Claude、16.5万美元,一次改变行业认知的激进实验
前端·后端·bun
Listen·Rain4 小时前
提示词和提示词模板
java·人工智能·spring boot
子兮曰4 小时前
Node.js v26.5.0 深度解读:import Text、流式 ReadableStreamTee、以及隐藏的安全加固浪潮
前端·后端·node.js