spring 服务层类应该是单例吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2173006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:59:11  来源:igfitidea点击:

Should service layer classes be singletons?

springn-tier-architecture

提问by oym

I am using Spring framework. Should my service classes be created as singletons? Can someone please explain why or why not? Thanks!

我正在使用 Spring 框架。我的服务类应该创建为单例吗?有人可以解释为什么或为什么不吗?谢谢!

回答by Bozho

Yes, they should be of scope singleton. Services should be stateless, and hence they don't need more than one instance.

是的,它们应该是 scope singleton。服务应该是无状态的,因此它们不需要多个实例。

Thus defining them in scope singletonwould save the time to instantiate and wire them.

因此在范围内定义它们singleton将节省实例化和连接它们的时间。

singletonis the default scope in spring, so just leave your bean definitions as they are, without explicitly specifying the scopeattribute.

singleton是 spring 中的默认范围,因此只需保留您的 bean 定义,而无需明确指定scope属性。

You can read more about scopes in the spring docs.

您可以在 spring 文档中阅读有关范围的更多信息。

回答by skaffman

Spring is easier to use if you stick with singleton-scoped beans. Singletons are its "default position", if you like. Yes, it supports other scopes (using scope="xyz"in the XML file), but it makes things harder to use and hurts performance.

如果您坚持使用单例范围的 bean,则 Spring 更易于使用。如果您愿意,单身人士是它的“默认位置”。是的,它支持其他范围(scope="xyz"在 XML 文件中使用),但它使事情更难使用并损害性能。

Essentially, unless you have a good reason to do otherwise, stick with singletons.

基本上,除非您有充分的理由不这样做,否则请坚持使用单身人士。

回答by sibidiba

You need mostly singletons. (Spring default.) Singletons must be thread-safe, because parallel requests will use the same single instance. In fact, they must be completely stateless, because it can be destroyed and recreated at any time.

您主要需要单身人士。(Spring 默认。)单例必须是线程安全的,因为并行请求将使用相同的单个实例。事实上,它们必须是完全无状态的,因为它可以随时被销毁和重新创建。

If you need to keep track of state inside of your bean (you should not, this should be in the database or stored in the request), you will get many instances of the same type of bean, memory usage goes up with the number of requests, whereby with singletons you will still have just one instance.

如果您需要跟踪 bean 内部的状态(您不应该,这应该在数据库中或存储在请求中),您将获得许多相同类型 bean 的实例,内存使用量随着数量的增加而增加请求,因此对于单例,您仍然只有一个实例。

Even if you scope you beans to a request, they must still need be at least thread-safe (requests coming from the same browser at the same time).

即使您将 bean 范围限定为一个请求,它们仍然必须至少是线程安全的(同时来自同一浏览器的请求)。