小工具知识网

当前位置: 首页 > 行业知识 > RequestContextHolder.getRequestAttributes()空指针

行业知识

RequestContextHolder.getRequestAttributes()空指针

2026-12-05 20:01:17 来源:互联网转载

现象:

HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

()

报空指针异常,java.lang.NullPointerException: null。

原因:

在代码中开启了子线程,在子线程中写了此段代码。

()

我这边是由于用了parallelStream,在并行流的业务代码中尝试获取Request。

解析:

1、RequestContextHolder.getRequestAttributes()为null,是由于保存requestAttributes的对象是线程隔离的ThreadLocal对象,当http请求发送到服务端时,每个请求会开启一个线程来处理,由RequestContextListener来初始化RequestContextHolder。

RequestContextHolder.setRequestAttributes(attributes);

当开启了子线程时,不会自动调用setRequestAttributes方法,所以从ThreadLocal中获取时为null

2、parallelStream是会开启子线程的,由于上述原因引发了异常

解决:

1、由主线程获取,传递给子线程

2、不要用并行流,parallelStream改为stream

上一篇:微信服务器号怎么用?

下一篇:揭秘士兵红包扫雷机器人的启动奥秘!