【发布时间】:2011-12-23 17:05:52
【问题描述】:
我有一个单例 bean,它有一个创建原型 bean 实例的方法。我正在使用方法documented here 来获取原型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的以下声明:
客户端代码必须清理原型范围的对象并发布 原型 bean 持有的昂贵资源。
所以听起来 Spring 会保留一个引用,所以 gc 永远不会拾取它?如果是这种情况,我如何告诉 Spring 释放引用?文档提到我可以使用“自定义 bean 后处理器”,但不清楚该处理器适用于何处以及它将运行什么代码。
提前感谢大家的帮助, 罗伊
【问题讨论】:
-
感谢您的精彩问题。您是否添加了一些额外的代码来手动破坏原型 bean?如果是,那你能解释一下吗?