简体   繁体   English

春天的单身豆

[英]Spring singleton bean

I know this question may sound naive, but I have a confusion regarding the scope of bean in web application. 我知道这个问题可能听起来很幼稚,但我对Web应用程序中bean的范围感到困惑。 I know that for every request a new thread is spawned by the container similarly in case of a spring web application a new thread is spawned for every request, then why it is suggested to define my controller, service as singleton, shouldn't the scope of these beans be prototype, because each request ie thread will have their own instance of controller, service to work with. 我知道,对于每个请求,容器会产生一个新线程,类似于Spring Web应用程序,每个请求都会生成一个新线程,那么为什么建议我将控制器定义为单例服务,不应该是范围这些bean是原型,因为每个请求即线程都有自己的控制器实例,服务可以使用。

Please enlighten me. 请赐教。

That would be a huge amount of overhead. 那将是巨大的开销。 There's no reason why each request needs its own service bean if you make your code properly thread-safe, which usually just means not keeping any per-request state on the bean. 如果您使代码正确地保证线程安全,那么每个请求都没有理由需要自己的服务bean,这通常意味着不会在bean上保留任何每个请求状态。

Even though a new thread is created (or re-used depending on the configuration), the controller and service instances are re-used. 即使创建了新线程(或根据配置重新使用),也会重新使用控制器和服务实例。 If the controllers and services are designed well, they can be stateless with respect to the request and immutable, which will make them thread-safe. 如果控制器和服务设计得很好,它们可以在请求和不可变的情况下是无状态的,这将使它们成为线程安全的。 It would also lead to far less object creations when their state is not going to change after their creation. 当它们的状态在创建后不会改变时,它也会导致更少的对象创建。

https://gottalovedev.wordpress.com/2014/11/23/bean-scope/ https://gottalovedev.wordpress.com/2014/11/23/bean-scope/

Give this a read. 给这个读一读。 I'm sure it would help. 我相信这会有所帮助。

I think this really depends whether you need to store any state in your bean. 我认为这取决于你是否需要在bean中存储任何状态。 Usually, I write my singletons so that they contain no state inside of it and are only used to compute business logic. 通常,我编写单例,以便它们不包含任何状态,仅用于计算业务逻辑。 Without state needing to be managed, then it is acceptable to have all threads share that one singleton instance. 如果没有需要管理的状态,那么让所有线程共享一个单例实例是可以接受的。

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

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