春豆范围.单例和原型 [英] Spring bean scope. Singleton and Prototype

查看:141
本文介绍了春豆范围.单例和原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设两个类为ClassA和ClassB.假设ClassB依赖于ClassA.在配置文件上,如果我们将ClassA的范围定义为单例,而将ClassB的范围定义为Prototype,那么每次创建ClassA的bean实例时,ClassB的实例会发生什么?每次返回ClassA实例时,都会返回相同的ClassB实例还是创建新实例?

Suppose two classes ClassA and ClassB. Lets suppose ClassB is dependent on ClassA. On configuration file, if we define scope of ClassA to be singleton and that of ClassB to be Prototype then what happens to instance of ClassB each time we create a bean instance of ClassA? Will the same ClassB instance gets returned or new instance is created each time instance of ClassA is returned?

谢谢!

推荐答案

如果ClassB是原型,则始终会创建ClassB的新实例,而在创建时不会处理其他类.

if ClassB is prototype, a newly instance of ClassB is always created, it does not take care of other classes at creation.

因此,ClassB是原型并且是ClassA单例,在某个时候,您的应用程序中可以有N个ClassB实例,而只有1个ClassA.

So ClassB being prototype and ClassA singleton, you could have N instances of ClassB and only 1 of ClassA in your application at some point.

在您的情况下,由于在应用程序生命周期中仅存在一个ClassA实例,因此它将只有一个实例ClassB,该实例与应用程序中其他bean引用的任何其他ClassB都不相同

In your case, as only one instance of ClassA will exist on your application life-cycle, it will only have one instance ClassB which will be different to any other ClassB referenced by other beans in your application

这篇关于春豆范围.单例和原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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