Home > database >  Initializing a boolean to use in every api call
Initializing a boolean to use in every api call

Time:12-28

I have a service shown below

public interface SomeService{

@GetMapping("/someapi")
public Object getData();
}

i have impl class shown below

public class ServiceImpl{

private boolen isSomeCondition;

public Object getData(){
callSomeMethod();
if(isSomeCondition)
//do something
else
//do some other
}
public void callSomeMethod(){
if(someCondition)
//do something
else
//set isSomeCondition to true
isSomeCondition=true;
}

i want this isSomeCondition to be set to false initially for every call to the "/someapi" and later to be changed when callSomeMethod is executed. whatever i have above doesn't seem to work as global variable isSomeCondition is stateless bean. what could be alternatives to this?

CodePudding user response:

If you require state, then introduce state. Create a stateful object for each request:

public class ServiceImpl{
  public Object getData(){
    final DataGetter getter = new DataGetter();
    return getter.getData();
  }

  static class DataGetter {
    private boolen isSomeCondition;

    public Object getData(){
      callSomeMethod();
      if(isSomeCondition) {
        //do something
      } else {
        //do some other
      }
    }

    public void callSomeMethod(){
      if(someCondition) {
        //do something
      } else {
        //set isSomeCondition to true
        isSomeCondition=true;
      }
    }
  }
}

Since you are using Spring, changing the bean scope might be an option too:

@RequestScope
public class ServiceImpl {
  // ...
}

CodePudding user response:

Try something like below. Instead of having isSomeCondition as global variable have it as local variable and pass it to the method.

public class ServiceImpl{

   public Object getData(){
   private boolen isSomeCondition;
   isSomeCondition = callSomeMethod(isSomeCondition);
   if(isSomeCondition)
   //do something
   else
  //do some other
  }

Here based on your condition you can set it and return.

 public boolean callSomeMethod(){
    if(someCondition)
    //do something
    else
   //set isSomeCondition to true
    isSomeCondition=true;
   return isSomeCondition;
  }
  • Related