How can I have a global variable in Spring per request?

Viewed 3633

I'm translating an application based on REST using Spring Framework. Now I need to translate some responses based on the language of the request. For example:

/get-me-an-answer/?lang=es Spanish
/get-me-an-answer/?lang=en English
/get-me-an-answer/?lang=fr French

I have the variable language_code as a static variable in a class named Translang

    class Translang {
...
        public static String language_code = null;
...
    }

The problem is with multithreading, when a new request come will change the language and if another previous request is executing can probably answer in the language modified and not in the original language it requested.

That's the reason of my question: How can I have a global variable in Spring per request to avoid this problem?

2 Answers

Seems that ThreadLocal is what you are looking for as per request is performed by a separate thread.

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

I would suggest to implement a context that navigates throw the flow of your request, so with this, you will pass this context among the entire transaction, once you have that domain element, you need to create a new one by each request that you receive. Currently your class is not thread safe, this can be fixed also changing the scope of your bean.

Related