关于Spring bean容器中的范围和垃圾回收 [英] Regarding the scope and garbage collection in Spring bean container

查看:306
本文介绍了关于Spring bean容器中的范围和垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对春天很陌生,目前我正在使用它在我的一个项目中。我了解到spring容器包含所有bean,默认情况下所有bean的范围都是单例。我可以在application-context.xml或使用@scope的annptation中更改范围。

I am new to spring and I am currently using it in one of my projects. I learned that the spring container holds all the beans and the scope of all the beans is singleton by default. I can change the scope either in the application-context.xml or using the annptation @scope.

现在我的问题是如果将类的范围设置为prototype ,每当需要一个新的对象时,弹簧容器就会实例化一个新对象......对吗?现在,如何处理垃圾收集。如果物品不再使用或物品仍然悬挂在容器中,这些物品是否会被垃圾收集?因为我不想每次都需要创建许多对象并加载内存。

Now my question is if have the scope of the class as "prototype", the spring container will instantiate a new object everytime ther is need for one ... right ?? Now, How is garbage collection handled. Will the objects be garbage collected if it is no longer used or will it be still hanging out in the container. Because I do not want many objects to be created everytime ther is need of one and load the memory.

有人帮助我理解这一点。
Thanks。

someone help me with understanding this please. Thanks.

推荐答案

从Spring文档( 3.5.2原型范围 ) :

From Spring documentation (3.5.2 The prototype scope):


与其他范围相比,Spring 不管理原型bean的完整生命周期:容器实例化,配置并以其他方式组装原型对象,然后将其交给客户端,不再记录该原型实例

简单地说 - 创建并获取对 prototype的引用 scoped bean它是JVM中唯一存在的参考。一旦这个引用超出了作用域,对象将被垃圾收集:

Simply put - once you create and obtain a reference to prototype scoped bean, it is the only reference existing in the JVM. Once this references gets out of scope, the object will be garbage collected:

void bar() {
  Object foo = ctx.getBean("foo")
}

当你离开 bar()方法中没有任何其他对 foo 的新实例的引用,这意味着它有资格进行垃圾回收。这个模型的结果是:
$ b

The moment you leave bar() method there aren't any other references to new instance of foo, which means it is eligible for garbage collection. The consequence of this model is:


因此,尽管初始化生命周期回调方法在所有对象上被调用,而不管在原型的情况下,配置的销毁生命周期回调是 not 调用的。

Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

这篇关于关于Spring bean容器中的范围和垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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