Using Spring Data Session bean in async task. Scope 'session' is not active for the current thread

Viewed 1270

I have the next flow to be implemented in my Spring MVC web app:

  • user inserts some value on the page, i.e. makes POST to the server
  • based on this value, controller starts a long running background task, i.e. really heavy (about one hour or so), so async is absolutely needed.
  • during this task, it is needed to read/write to database (in my case it is Neo4j)

How did I make it:

  1. we have bean in scope 'session':
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
    return super.getSession();
}
  1. In my controller I have some db repositories:
@Autowired
SomeDBRepo repo;
  1. I have a method, annotated by @Async
@Async 
doSomeAsync() {
   repo.findAll();
}

and I am getting this error:

Error creating bean with name 'scopedTarget.getSession': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I have already read some articles about this issue, but nothing helped to me. How this problem could be solved?

1 Answers

The session and request scopes in Spring are thread bound.

When you annotate a method with @Async the execution takes place in another thread, and cannot access the scopes of the caller (and thus the session).

Try to inject the SessionFactory in your async bean to get a Session.

BTW, are you sure you really need a session scope ? This stores the OGM session in the web session, which can lead to memory problems under load, as the session acts as a first level cache of the database.

Related