Scope of Spring -Controller and its variable instances

Are all the controllers in Spring-MVC singleons and split between different sessions and requests?

If so, I am assuming a class variable like

public String name; 

will be the same for all requests and sessions? So, if user X makes a request and name set to Paul, does user Z also have the Paul attribute as an attribute?

In my case, I DO NOT want this behavior, but I wonder if there is a simpler or cleaner OOP way to have session / request variables and then session.getAttribute() / request.getAttribute()

+35
spring spring-mvc
Jun 21 2018-12-12T00:
source share
2 answers

To answer your first question: yes, Spring MVCs are single by default. The object field will be shared and visible for all requests and all sessions forever.

However, without any synchronization, you may encounter all types of concurrency problems (race conditions, visibility). Thus, your field must have a volatile (and private volatile , by the way) to avoid visibility problems.

Back to the main question: in Spring, you can use request- (see 4.5.4.2 request scope ) and session scope (see: 4.5.4.3 Session scope ) beans. You can enter them to controllers and any other beans (even singlots!), But Spring ensures that each request / session has an independent instance.

The only thing to remember when introducing beans into a single package with a query and session is to wrap them in a cloud proxy (example from 4.5.4.5 Scoped beans as dependencies ):

 <!-- an HTTP Session-scoped bean exposed as a proxy --> <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> <!-- instructs the container to proxy the surrounding bean --> <aop:scoped-proxy/> </bean> 
+51
Jun 21 2018-12-12T00:
source share

Yes, the controllers in Spring-MVC are single. Between multiple requests, your class variable is shared and may lead to ambiguity. You can use the @Scope annotation (โ€œrequestโ€) over your controller to avoid such ambiguity.

+7
Jun 25 '15 at 4:00
source share



All Articles