Spring - 如何销毁原型(prototype)范围的 bean?

标签 spring garbage-collection

我有一个单例 bean,它有一个创建原型(prototype) bean 实例的方法。我用的方法documented here获取原型(prototype) bean 的实例。

public class SingletonService implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void go() {

        MyPrototypeBean prototype = applicationContext
            .getBean(MyPrototypeBean.class);

        prototype.doSomething();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {

        this.applicationContext = applicationContext;
    }
}

起初我认为这已经足够好了,当 'go' 方法返回时,我的 'prototype' 实例将超出范围,这意味着该实例将没有引用并且会被垃圾回收。

然而,一位同行指出 the documentation 中的以下声明:

The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.

所以听起来 Spring 会保留一个引用,所以 gc 永远不会拾取它?如果是这种情况,我如何告诉 Spring 释放引用?文档提到我可以使用“自定义 bean 后处理器”,但不清楚该处理器适用于何处以及它将运行什么代码。

提前感谢大家的帮助, 罗伊

最佳答案

我认为您误解了文档。只是说Spring不会管理原型(prototype)bean的生命周期,因此@PreDestroy(等)方法需要由您自己的代码调用。 Spring 不会保留引用。

关于Spring - 如何销毁原型(prototype)范围的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618735/

相关文章:

spring - 进行微服务 REST API 版本控制的最佳方法是什么?

java - Swagger UI 错误请求 URL 生成

Spring Redirect 命令重定向到 Load Balancer 下的 Localhost

java - java页面上下文属性的垃圾收集

.NET 垃圾收集 - 它会影响什么?

asp.net - 在 IIS 8.5 和 Windows Server 2012 R2 上运行的 ASP.NET 应用程序的默认 GC 模式

java - Spring 一对一关系

java - JPA 合并在 ApplicationListener 中不起作用,但在 Controller 中起作用

Go 的垃圾收集器在使用时删除 ZeroMQ 套接字

Java 8 元空间垃圾回收