Spring-Controller的范围及其实例变量 [英] Scope of a Spring-Controller and its instance-variables
问题描述
Spring-MVC中的所有控制器是否都是单例的,并且在不同的会话和请求之间共享?
Are all controllers in Spring-MVC singletons and are shared among different sessions and requests?
如果是这样,我认为像这样的类变量
If so, I assume that a class-variable like
public String name;
所有请求和会话都相同吗?这样,如果用户X发出请求并将name
设置为 Paul ,那么用户Z还将Paul作为属性吗?
would be the same for all requests and sessions? So that if User X makes a request and name
is being set to Paul, User Z also has Paul as attribute?
在我的情况下,我不希望这种行为,但想知道是否有比session.getAttribute()
/request.getAttribute()
In my case I do NOT want that behaviour but wondered if there is a more easier, or more cleaner OOP-way to have session/request-variables then session.getAttribute()
/request.getAttribute()
推荐答案
回答第一个问题:是的,Spring MVC控制器默认为单例.对象字段将为所有请求和所有会话永久共享并可见.
To answer your first question: yes, Spring MVC controllers are singletons by default. An object field will be shared and visible for all requests and all sessions forever.
但是,如果不进行任何同步,则可能会遇到各种各样的并发问题(竞争条件,可见性).因此,您的字段应该具有volatile
(顺便说一下,还有private
)修饰符,以避免可见性问题.
However without any synchronization you might run into all sorts of concurrency issues (race conditions, visibility). Thus your field should have volatile
(and private
, by the way) modifier to avoid visibility issues.
回到您的主要问题:在Spring中,您可以使用 request-(请参阅 4.5.4.3会话范围 )豆.您可以将它们注入控制器和任何其他bean(甚至是单例!),但是Spring确保每个请求/会话都有一个独立的实例.
Back to your main question: in Spring you can use request- (see 4.5.4.2 Request scope) and session-scoped (see: 4.5.4.3 Session scope) beans. You can inject them to controllers and any other beans (even singletons!), but Spring makes sure each request/session has an independent instance.
将请求和会话范围的bean注入单例时,要记住的是将它们包装在作用域代理中(示例取自
Only thing to remember when injecting request- and session-scoped beans into singletons is to wrap them in scoped proxy (example taken 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>
这篇关于Spring-Controller的范围及其实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!