0

Here's the problem I'm trying to solve:

I've got a number of entry points into my system. e.g REST endpoints, Queue listeners, and let's suppose more in the future. I'd like to set some contextual information to make available to all service methods (these can call other service methods in turn, creating a DAG of calls).

One way to think about this would be for all my service methods to take an extra context parameter, which they then pass down.

Another (less powerful) way to think about this would be to save this information on a bean under WebApplicationContext.SCOPE_REQUEST. As I understand them, these won't maintain the bean for asynchronously running CompletableFutures. These also won't work for non-http requests (e.g the queue).

It looks like my options are:

  1. Refactor all my methods to take in a new context param. Downside is that this is a massive refactor where most methods will take in a param and do nothing more than pass it down.
  2. Implement a new spring scope (like WebApplicationContext.SCOPE_REQUEST). I'd like to refrain from adding this sort of complexity unless actually needed.

Are there other cleaner options I'm just not seeing? I can't help but feel this should be a common problem with solution patterns.

2
  • 1
    ThreadLocal variables are a current option. In the (near) future, Scoped Values will be a better option. Commented Nov 21, 2024 at 18:05
  • Seems like your need is to be able to have thread isolation of contextual data. I would try to create a normal Bean (which has singleton scope as default) with the attributes you want to store wrapped in a ThreaLocal as @jaco0646 is suggesting. Of course you would need to inject that bean in all your components or at least in those worried about the contextual data. Commented Jul 13 at 19:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.