Async process using Spring and injecting user context

Hari Ohm Prasath
Javarevisited
Published in
4 min readDec 3, 2019

--

Why do we need a separate post on this?

  • The general practice that’s followed in java world to start an async process is to create a separate thread or implement the class using Runnable method. But this approach will not work for spring because, the whole idea of using spring is to leverage the power of “Dependency injection”, so if we create a thread outside its context spring won’t be able to autowire fields inside the class.
  • Most of the web applications use AspectJ as a common practice to inject user context based on the login information by using “ThreadLocal” variables. This approach will work fine in most of the cases, but in this scenario where a new thread is created by spring, which we don’t have any handle those “ThreadLocal” variables will not be available in the newly created thread. So how can we notify spring to pass on the user context to the newly created thread?

Considering these things I would like to explain how can we do this is a rightful and simple way without disturbing too much of the existing code or architecture. Like any problem there are multiple approaches to solve this and here is my take on this.

Creating an async process using spring

--

--