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?
在我的情况下,我不想要这种行为,但想知道是否有更简单或更干净的 OOP 方式来拥有会话/请求变量,然后 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.2 请求范围) 和 session-scoped(参见:
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 注入单例时,唯一要记住的是将它们包装在范围代理中(示例取自 4.5.4.5 作用域 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屋!