简体   繁体   English

何时在 Spring MVC 中为控制器使用请求范围的 bean 而不是 singleton bean

[英]When to use request scoped beans over singleton beans for Controllers in Spring MVC

Is it to ensure that the controllers are thread safe?是为了确保控制器是线程安全的吗?

If the above case is true, then is it necessary to go through the overhead of bean creation for each request rather than making the controller code not rely on instance variables?如果上述情况属实,那么是否有必要通过为每个请求创建 bean 的开销来 go 而不是使 controller 代码不依赖实例变量?

Your default position should be to use singleton controllers which are thread-safe.您的默认 position 应该使用线程安全的 singleton 控制器。 This partly for performance reasons, as you say, and partly for reasons of good design - a large mass of stateful, request-scoped beans is a mess.正如您所说,这部分是出于性能原因,部分是出于良好设计的原因 - 大量有状态的、请求范围的 bean 是一团糟。

Using request-scoped controllers (or other request-scoped beans) is a specialised requirement which you should only use when you have good reason to do so, ie you have beans whose state must be private to the lifecycle of that particular request.使用请求范围的控制器(或其他请求范围的 bean)是一项特殊要求,只有在您有充分理由这样做时才应使用它,即您拥有的 bean 的 state 必须是该特定请求的生命周期专用的。

Request scoped beans are short living instances of a class, they will be created when a new request comes in.请求范围的 bean 是 class 的短暂实例,它们将在新请求进入时创建。

Singleton beans live the entire lifetime of your application. Singleton bean 在应用程序的整个生命周期中都存在。 Note: If you have a multi user application with several sessions, all users will access the same instance of your beans, if they are singletons.注意:如果您有一个包含多个会话的多用户应用程序,那么所有用户都将访问您的 bean 的同一个实例(如果他们是单例)。

I would prefer Request scoped beans whenever possible in a web application.我希望尽可能在 web 应用程序中请求范围 bean。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM