我有一个单例 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/