2011-07-15 32 views
0
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()而不是銷燬方法。下面是我​​3210爲什麼在銷燬方法不會在下面自動調用時,對象會毀滅?

<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(); 
+0

你何時期待'摧毀()'被稱爲? – skaffman

+0

感謝您的回覆。根據我的知識,當bean名稱「dhiraj」被實例化時,應調用afterPropertiesSet(),並在銷燬bean dhiraj之前調用destroy()方法。第一種方法是正確調用,但不是第二種。 –

+0

可能的重複[何時是一個春天豆摧毀方法叫?](http://stackoverflow.com/questions/4460384/when-is-a-spring-beans-destroy-method-called) –

回答

2

對於單豆像dhiraj,該destroy()生命週期的方法將被調用時,只有當,應用程序上下文被關閉。

如果您的代碼片段是整個程序,那麼將不會調用destroy(),因爲您沒有正確關閉上下文。

context.close()添加到片段末尾,您將看到destroy()被調用。

5

試試這個:

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

您必須手動關閉的背景下,否則Spring不知道bean是不再需要,應該被銷燬。請注意,您必須使用AbstractApplicationContext類型作爲ApplicationContext接口未定義close()

+0

非常感謝。他的工作 –

1

您也可以註冊關閉鉤子是這樣的:

AbstractApplicationContext上下文=新的ClassPathXmlApplicationContext( 「春-config.xml文件」); context.registerShutdownHook();

0

您需要關閉上下文對象,那麼只有破壞方法被調用。 Check for img

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

**