关于在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对象。

相关推荐
麦兜*7 分钟前
SpringBoot Profile多环境配置详解,一套配置应对所有场景
java·数据库·spring boot
MetaverseMan7 分钟前
rpc节点: synchronized (this) + 双检锁,在 race condition 的情况下分析
java·区块链
笃行客从不躺平8 分钟前
Seata + AT 模式 复习记录
java·分布式
CTO Plus技术服务中11 分钟前
强悍的Go语言开发面试题和答案
java·面试·职场和发展
无心水11 分钟前
2、Go语言源码文件组织与命令源码文件实战指南
开发语言·人工智能·后端·机器学习·golang·go·gopath
黎雁·泠崖20 分钟前
Java static入门:概述+静态变量特点与基础实战
java·开发语言
努力也学不会java21 分钟前
【Spring Cloud】 服务注册/服务发现
人工智能·后端·算法·spring·spring cloud·容器·服务发现
一条大祥脚25 分钟前
26.1.21 根号分治 相向双指针
java·开发语言·redis
迦蓝叶32 分钟前
JDBC元数据深度实战:企业级数据资源目录系统构建指南
java·jdbc·企业级·数据资源·数据血缘·数据元管理·构建指南