java - 在 Threads 中访问作用域代理 bean

标签 java spring spring-mvc threadpool

我有一个在 tomcat 中运行的 Web 应用程序,我使用 ThreadPool (Java 5 ExecutorService) 并行运行 IO 密集型操作以提高性能。我想让每个池线程中使用的一些 bean 在请求范围内,但是 ThreadPool 中的线程无权访问 spring 上下文并获得代理失败。关于如何使 ThreadPool 中的线程可以使用 spring 上下文以解决代理故障的任何想法?

我猜肯定有一种方法可以为每个任务在 ThreadPool 中注册/取消注册每个线程,但没有任何运气找到如何做到这一点。

谢谢!

最佳答案

我正在为需要访问请求范围的任务使用以下父类(super class)。基本上你可以扩展它并在 onRun() 方法中实现你的逻辑。

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();
}

关于java - 在 Threads 中访问作用域代理 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1528444/

相关文章:

java - 从 JTextPane 获取不带 HTML 标签的文本

java - 为什么在将 List 转换为 MultiKeyMap 时不会出现编译错误?

基于操作的javax验证

oracle hibernate + maven dependenciesm dbcp.basicdatasource 异常

spring - spring.ftl 的绑定(bind)宏中调用的 springMacroRequestContext 是什么?

java - 如何在 Spring Boot 中的 application.yml 中添加 GCP(Google Cloud Storage)存储属性

java - 如何跨多个线程访问相同的 POJO 实例

Java : JsonPareser contains no data

java - Crudrepository - 没有找到依赖项类型的合格 bean : expected at least 1 bean which qualifies as autowire candidate for this dependency

java - Autowiring 依赖项注入(inject)失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException : Could not autowire field: