Accessing scoped proxy beans within Threads of

后端 未结 4 1235
庸人自扰
庸人自扰 2020-12-02 13:45

I have a web application running in tomcat where I\'m using a ThreadPool (Java 5 ExecutorService) to run IO intensive operations in parallel to improve performance. I would

4条回答
  •  [愿得一人]
    2020-12-02 14:27

    I am using the following super class for my tasks that need to have access to request scope. Basically you can just extend it and implement your logic in onRun() method.

    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.RequestContextHolder;
    
    /**
     * @author Eugene Kuleshov
     */
    public abstract class RequestAwareRunnable implements Runnable {
      private final RequestAttributes requestAttributes;
      private Thread thread;
    
      public RequestAwareRunnable() {
        this.requestAttributes = RequestContextHolder.getRequestAttributes();
        this.thread = Thread.currentThread();
      }
    
      public void run() {
        try {
          RequestContextHolder.setRequestAttributes(requestAttributes);
          onRun();
        } finally {
          if (Thread.currentThread() != thread) {
            RequestContextHolder.resetRequestAttributes();
          }
          thread = null;
        }
      }
    
      protected abstract void onRun();
    }
    

提交回复
热议问题