【发布时间】: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