gpt4 book ai didi

java - Spring 原型(prototype) Bean 和 Spring 的好处

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:35 25 4
gpt4 key购买 nike

我已经逐渐掌握了 Spring 一段时间了,我认为我对这些概念有一个合理的想法,但是我在我的另一个线程中遇到了一些信息,这对我来说是天翻地覆的......

"...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. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up."

这让我想到我有真实的用例,我想在其中使用原型(prototype) bean,例如,每个请求我需要一个"new"bean 实例。然而,根据我对这个片段的理解(来自 Spring 3 文档),Spring 保留了对需要清理的 beans 的引用(引用本身意味着垃圾收集器不会自动清除 bean)。此外,我由此得出结论,必须手动清理原型(prototype) bean 持有的资源。

有人可以告诉我这是否正确吗?如果是这样,是否有用于处理此问题的典型模式?如果能描述 Spring 以这种方式实现原型(prototype) bean 的架构原因,我将不胜感激。

最佳答案

Spring holds on to a reference to beans that need to be cleaned up (the reference itself meaning that the bean will not be cleared automatically by the garbage collector).

是的,但容器不包含对原型(prototype)作用域 bean 的引用。这就是不调用销毁回调的原因:Spring 创建 bean 实例,连接它并调用构造回调。它提供了一个实例并忘记了那个 bean。

您可以根据请求安全地创建原型(prototype)范围的 bean。 Spring 会给你一个实例,当你没有对该 bean 的任何引用时(Spring 不保留一个!),它将被垃圾收集。但是由于 Spring 在创建 bean 后对它一无所知 - 它无法调用任何销毁回调。事实上,这归结为一个问题:为什么 Java 没有析构函数。

那么如何清理原型(prototype)作用域的 bean?好吧,就像您在 Java 中明确地清理任何其他资源一样。提供 close()destroy()stop() 或您喜欢的任何名称(考虑实现 Closeable 。请注意,此类方法不是' 通常需要。垃圾收集器将释放整个对象图,而当整个 DataSource 关闭时,数据库连接等持久资源将关闭。

关于java - Spring 原型(prototype) Bean 和 Spring 的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com