title: Spring promoting request scoped bean to child threads (HttpServletRequest)
body: <p>I tried a lot of things now but i seem to miss a piece of the puzzle. Here is the story: I have a request scoped bean that reads some SessionContext from the HttpServletRequest. This attribute is set in a filter. So this is working absolutely fine while the code runs on the correct thread.</p>
  
  <pre><code>@Component
  @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.INTERFACES)
  public class SessionContextProviderImpl implements SessionContextProvider&lt;SessionContext&gt; {
      private final HttpServletRequest _request;
  
      @Autowired
      public SessionContextProviderImpl(HttpServletRequest request) {
          _request = request;
      }
  
      @Override
      public SessionContext get() {
          return (SessionContext) _request.getAttribute(Constants.SESSION_CONTEXT_IDENTIFIER);
      }
  }
  </code></pre>
  
  <p>Now I started using java 8s new feature CompletableFuture and i have three of those features computing stuff in parallel while the request thread waits for the result. What i want to do is to promote/hand over/propagate the bean or request in a way that it can be used on child threads that have been spawned from the original http thread. In particular I would like to get the SessionContext from the HttpServletRequest from inside an asynchronous supplied CompletableFuture.</p>
  
  <p>what i tried is this (replaced implementation of get):</p>
  
  <pre><code>final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  request.getAttribute(Constants.SESSION_CONTEXT_IDENTIFIER);
  </code></pre>
  
  <p>But this has obviously the same result as the request scoped bean. Well "getRequest" returns null instead of an exception thrown.</p>
  
  <p>As a third approach I tried this <a href="https://stackoverflow.com/questions/14986519/spring-mvc-how-to-use-a-request-scoped-bean-inside-a-spawned-thread">original post</a>:</p>
  
  <pre><code>ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;
  
  org.springframework.beans.factory.config.Scope simpleThreadScope = new SimpleThreadScope();
  
  cbf.registerScope("simpleThreadScope", simpleThreadScope);
  </code></pre>
  
  <p>And i set the scope of the SessionContextProviderImpl to be "simpleThreadScope". Unfortunately this did not work either and threw an exception that it is used outside of a request scope.</p>
  
  <p>The environment I am using: Jersey together with spring injection.</p>
  
  <p>Maybe anyone has some idea?</p>
  
  <p>regards</p>