Spring MVC 控制器是单例吗? [英] Are Spring MVC Controllers Singletons?

查看:27
本文介绍了Spring MVC 控制器是单例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Spring 3 MVC @Controllers 的查询.当请求进来时,容器是为每个请求创建控制器的新实例(类似于 Struts 2 中的 Action - ThreadLocal ActionContext)还是单个实例响应对所有请求?默认情况下,控制器 bean 在上下文中是单例的吗?

I have a query regarding Spring 3 MVC @Controllers. When a request comes in, does the container create a new instance of the controller for each request (Similar to an Action in Struts 2 - ThreadLocal ActionContext) or a single instance responds to all requests? By default are the controller beans singletons in a context?

Spring 3 MVC 应用程序的指南/最佳实践是什么?这些设置是否可配置?应该配置那些吗?如果我的环境是集群环境,它是否会发生很大变化 - 我想它不应该因为 jvm/容器会有所不同 - 但欢迎一些权威建议.

What are the guidelines/ best practices for a Spring 3 MVC application? Are these settings configurable? Should those be configured? Does it change much if my environment is a clustered environment - I guess it should not as the jvm/containers would be different- but some authoritative suggestion would be welcome.

我已阅读 Spring 文档,但可能我错过了.任何这就是我们实施的方式"的答案/指针/链接都会有所帮助谢谢.

I have read Spring documentation but probably I missed it. Any 'this is how we implemented kind of' answers/ pointers/ links would be helpful Thanks.

推荐答案

Spring 控制器是单例的(每个 Web 应用程序只有一个控制器的实例),就像 servlet 一样.通常没有必要改变这种行为(如果可能的话).请参阅关于 servlet 的线程安全,了解常见陷阱,也适用于控制器.

Spring controllers are singletons (there is just one instance of each controller per web application) just like servlets. Typically there is no point in changing this behaviour (if it's even possible). See Regarding thread safety of servlet for common pitfalls, also applying to controllers.

如果您的应用程序是集群的,请尽可能避免状态.控制器中的状态需要同步以避免线程问题.此外,您可能会跨服务器复制该状态 - 非常昂贵且麻烦.

If your application is clustered do as much as you can to avoid state. State in controllers will require synchronization to avoid threading issues. Also you'll probably replicate that state across servers - very expensive and troublesome.

这篇关于Spring MVC 控制器是单例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆