【问题标题】:Why in destroy method is not called automatically in below when object will destroy?为什么当对象将要销毁时,下面的销毁方法不会自动调用?
【发布时间】:2011-07-15 06:26:17
【问题描述】:
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() 而不是销毁方法的输出。下面是我的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();

【问题讨论】:

  • 您希望何时调用destroy()
  • 感谢您的重播。据我所知,当实例化 bean 名称“dhiraj”时,应该调用 afterPropertiesSet() 并在销毁 bean dhiraj 之前调用 destroy() 方法。第一种方法调用正确,但第二种方法调用不正确。

标签: spring


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    试试这个:

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

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

    【讨论】:

      【解决方案3】:

      你需要关闭Context对象,然后才调用destroy方法Check for img

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

      **

      【讨论】:

        【解决方案4】:

        你也可以这样注册关机钩子:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-09
          • 2012-01-30
          • 1970-01-01
          • 1970-01-01
          • 2011-05-26
          相关资源
          最近更新 更多