【发布时间】:2014-02-03 12:36:40
【问题描述】:
当一个 bean 被声明为内部 bean 时,它应该随着外部 bean 的销毁而被销毁。但是在下面没有调用 bean 的销毁方法的情况下不会发生这种情况。
innerbeans-spring.xml
<bean id="car" name="carBean" class="com.semanticbits.shoaib.innerbeans.Car" destroy-method="destroy" init-method="init">
<property name="engine">
<bean class="com.semanticbits.shoaib.innerbeans.Engine" destroy-method="destroy" init-method="init">
</bean>
</property>
</bean>
Car.java:这里只需要编写代码
public void init(){
System.out.println("Car init method");
}
public void destroy(){
System.out.println("Car destroy method");
}
public static void main(String[] args){
ConfigurableApplicationContext context=(ConfigurableApplicationContext)ApplicationContextFactory.getApplicationContext("innerbeans-spring.xml");
Car car=context.getBean("car",Car.class);
context.getBeanFactory().destroyBean("car",car);
}
Engine.java:这里只需要编写代码
public void init(){
System.out.println("Engine init method");
}
public void destroy(){
System.out.println("Engine destroy method");
}
输出:
Engine init method
Car init method
Car destroy method
我的问题是:
1) getBeanFactory().destroyBean(String beanName,Object beanReference)
beanName 在这里是什么意思?
2) 为什么 Engine 类的 destroy 方法不被调用,因为 Engine 是 Car 类的内部 bean??
扩展问题:
public static void main(String[] args){
ConfigurableApplicationContext context=(ConfigurableApplicationContext)ApplicationContextFactory.getApplicationContext("innerbeans-spring.xml");
Car car=context.getBean("car",Car.class);
context.getBeanFactory().destroyBean("car",car);
//now here Car bean is destroy.
//when I call then check the output section.
context.getBeanFactory().destroySingletons();
}
扩展输出:
Engine init method
Car init method
Car destroy method
Car destroy method
Engine destroyed.
3)当 Car 实例已经被销毁时,为什么要再次调用 Car 的 destroy() 方法?
提前致谢。
【问题讨论】:
-
如果需要额外的代码,请告诉我。
-
既然没有提到
Enginebean,那不就是说Enginebean 被破坏了吗?垃圾会收集任何内部类,Carbean 的变量。 -
那么为什么Engine类没有调用destroy()方法
标签: java spring inversion-of-control