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

相关推荐
程序员cxuan4 分钟前
DeepSeek Harness 必装的插件公布了!
人工智能·后端·程序员
墨雨晨曦8810 分钟前
2026/08/15 spring AI学习总结
java·tomcat
fatcoder21 分钟前
玩转Nginx 03 — location 匹配规则:让不同的路径各回各家
前端·后端·nginx
wno70426 分钟前
Spring Boot JdbcTemplate配置Druid多数据源
java·spring boot·后端
月才29 分钟前
Spring Boot 接口参数校验从入门到精通
后端
码农大叔的博客31 分钟前
golang示例:switch
开发语言·后端·golang
Zane199436 分钟前
多开几个线程,为什么算数字反而没变快?一文讲透 CPython 的 GIL
后端·python
wear工程师37 分钟前
Spring Boot 服务挂了却没重启?先分清 systemd 的三次判断
spring boot
一只叫煤球的猫38 分钟前
Spring AI 2.0 源码解析(二):Starter 如何自动装配 ChatClient ?
后端·面试·langchain
聊浮游1 小时前
JAVA2026最新全套学习资料、学习路线
java·开发语言·jvm·mysql·spring·maven·idea