Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing scoped proxy beans within Threads of

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 like to have some of the beans used within each pooled thread be in the request scope, but the Threads in the ThreadPool do not have access to the spring context and get a proxy failure. Any ideas on how to make the spring context available to the threads in the ThreadPool to resolve the proxy failures?

I'm guessing there must be a way to register/unregister each thread in the ThreadPool with spring for each task, but haven't had any luck finding how to do this.

Thanks!

like image 896
Perulish8 Avatar asked Oct 06 '09 22:10

Perulish8


People also ask

What is scoped proxy?

Marker annotation identical in functionality with <aop:scoped-proxy/> tag. Provides a smart proxy backed by a scoped bean, which can be injected into object instances (usually singletons) allowing the same reference to be held while delegating method invocations to the backing, scoped beans.

What is session scope in Spring boot?

Global session scope defines a single bean definition to the lifecycle of a global HTTP Session. This scope is valid when used in a portlet context. When your application is built of portlets, they run in Portlet container.

How do you inject request in scoped bean?

As singleton beans are injected only once per their lifetime you need to provide scoped beans as proxies which takes care of that. @RequestScope is a meta-annotation on @Scope that 1) sets the scope to "request" and 2) sets the proxyMode to ScopedProxyMode.


1 Answers

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();
}
like image 126
Eugene Kuleshov Avatar answered Oct 20 '22 14:10

Eugene Kuleshov