当对象破坏时,为什么在下面不会自动调用destroy方法?

时间:2011-07-15 06:26:18

标签: spring

public class Instrumentalist implements Performer, InitializingBean, DisposableBean {
 private Instrument instrument;
 private String song;
 public void setInstrument(Instrument instrument)
 {
     this.instrument=instrument;
 }

 public void setSong(String song)
 {
     this.song=song;
 }

 public void afterPropertiesSet() throws Exception
 {
     System.out.println("Before Playing Instrument");
 }

 public void destroy() throws Exception
 {
     System.out.println("After Playing Instrument");
 }

  public void perform() {
    // TODO Auto-generated method stub
    System.out.println("Playing "+ song + " : ");
    instrument.play();
   }

}

在上面的示例中,我只得到了调用afterPropertiesSet()而不是destroy方法的输出。以下是我的config.xml

<bean id="dhiraj" class="Instrumentalist">
    <property name="song" value="Sa Re Ga Ma" />
    <property name="instrument" ref="piano" />
</bean>

<bean id="piano" class="Piano" />

我从我的main方法调用如下 -

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-config.xml");
Performer performer1=(Performer)context.getBean("dhiraj");
performer1.perform();

4 个答案:

答案 0 :(得分:5)

试试这个:

AbstractApplicationContext context = new ClassPathXmlApplicationContext("Spring-config.xml");
//...
context.close();    //!!!

您必须手动关闭上下文,否则Spring不知道该bean不再需要并且应该被销毁。请注意,您必须使用AbstractApplicationContext类型,因为ApplicationContext界面未定义close()

答案 1 :(得分:2)

对于像dhiraj这样的单例bean,当且仅当应用程序上下文关闭时,才会调用destroy()生命周期方法。

如果您的代码片段是整个程序,则不会调用destroy(),因为您没有正确关闭上下文。

context.close()添加到您的片段末尾,您会看到destroy()被调用。

答案 2 :(得分:1)

您也可以这样注册shutdown hook:

  

AbstractApplicationContext context = new ClassPathXmlApplicationContext(“Spring-config.xml”);   context.registerShutdownHook();

答案 3 :(得分:0)

您需要关闭上下文对象,然后才会调用 销毁方法 Check for img

ConfigurableApplicationContext Context= new ClassPathXmlApplicationContext("ApplicationContext.xml");
//.............
//.........
Context.close();

**