Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java getRequestAttributes()有时为null_Java_Spring - Fatal编程技术网

Java getRequestAttributes()有时为null

Java getRequestAttributes()有时为null,java,spring,Java,Spring,在我的JavaSpring项目中,我使用 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()) .getRequest(); 它在静态方法中定义,用于获取请求和某些会话属性。spri

在我的JavaSpring项目中,我使用

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                                         .getRequestAttributes())
                                         .getRequest();
它在静态方法中定义,用于获取请求和某些会话属性。spring RequestContextListener已存在于my web.xml中。问题是当一些单线程调用它时,现在一切都很好


但是当使用java8 parallelStream时,
RequestContextHolder.getRequestAttributes()
有时可能为空,我不知道为什么。

您的项目是spring还是spring boot? 如果是spring引导,则使用RequestContextListener或RequestContextFilter公开bean

@Bean
  public RequestContextListener requestContextListener() {
    return new RequestContextListener();
  }

还要确保没有任何@Configuration类与@EnableWebMvc一起使用。这将删除spring boot自动配置功能。

我认为parallelStream使用ThreadLocal来执行线程,并且它不是可变线程扩展的。解释了问题。知道如何从该线程中访问请求对象吗?@Hamid您需要将请求/会话分配给静态对象。但最好不要使用parallelStream来执行一些业务逻辑。