Reputation: 1363
Below you can see Something
class which is a request
scoped bean I've been facing one issue with.
Once I set the static boolVariable
field its value survives along sessions.
Scenario:
User in the application does something that sets variable to true, then it logs out, clears every data (cookie, cache...). When it logs again into application, boolVariable
is still true
(he did not set his value again), while I expect it to be false.
Quote from concretepage:
Within HTTP request, the changes done in request scoped bean does not affect the other HTTP request. Once HTTP request is completed, the instance of request scoped bean is also destroyed.
Here is the Something
class:
@Service(value = "Something")
@Scope(value = "request")
public class Something {
private static boolean boolVariable = false;
public Something() {
}
public static void setBoolVariable(boolean toBeSaved) {
boolVariable = toBeSaved;
}
private boolean isBoolVariable() {
return boolVariable;
}
}
Could you please explain why behaviour described above happens?
(When I restart the server, boolVariable
value is restored back to false
)
Upvotes: 1
Views: 4567
Reputation: 5753
Static variables are initialized when the class is loaded into the JVM. The state is global and is shared by all instances for the lifetime of the JVM process.This explains why the static variable is reinitialized when you restart the JVM
Your bean is request scoped. Its the bean instances that are recreated per request not the global state (static variables).Why did you even have to make the variable static. This seems to be conversational state (state specific to a client). When its static you also have to worry about thread safety.
Change to instance variable so that each requested scoped bean as its own state. Otherwise if its shared state then your bean is a candidate for singleton scope not request scoped
Static variables are not handled in a special way by Spring. It uses standard Java semantics
Upvotes: 6