我有一个在 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/