简体   繁体   中英

string being in previous state even after triggering a new request java

I am working on a spring boot api where I have used a query string and doing some replace operations on it on every get request but even after I trigger a new request the string is in the same state as that of previous GET call and the query gets messed up.

Here's my code:

 private static String GET_SETS = "Select * from table #check#";

Now I have 1 method in the same repository which gets called on a get request:

public PagedList getSets(Map params) {
    if (!StringCheck.isEmpty(flattenMap.get("entity_name"))) {
        GET_SETS = GET_CODE_SETS.replace("#check#", " WHERE e.#entity_name# = ?");
        values.add((String)flattenMap.get("entity_name"));
    } else {
        GET_SETS = GET_SETS.replace("#check# #status_check#", "");
    }
}

Now whenever a GET request is triggered,some changes are done to GET_SETS string according to map values,and again in the next requests the same changes are there.

How to solve this? I want the query string to be whats defined at the start on every request. Thanks

Your problem is most likely caused by using the default scope, which is singleton, when creating your Spring components.

Spring provides the following scopes for creating beans ( source ):

  • singleton (default): Scopes a single bean definition to a single object instance for each Spring IoC container
  • prototype: Scopes a single bean definition to any number of object instances.
  • request: Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
  • session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  • application: Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
  • websocket: Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

If we don't specify any scope explicitly, the default singleton scope is used. This means that the service/component is shared between multiple injections, hence it is reused for multiple GET requests.

In order to get rid of this behavior, we might use something like request scope, although in this case we have to take care of thread-safety as well.

Other solution is to not use member variables and try to use local variables for things such as GET_SETS .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM