1.实现InitializingBean,DisposableBean接口,覆写方法
具体实现如下:
public class SetByJava implements InitializingBean,DisposableBean{
public void destroy() throws Exception {
System.out.println("destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("init");
}
public void doSomething() {
System.out.println("doSomething");
}
}
配置bean
<bean id="text" class="InitAndDestroy.SetByJava">
</bean>
测试,实例化ConfigurableApplicationContext,调用其close方法模拟销毁。
ConfigurableApplicationContext app = new ClassPathXmlApplicationContext("initText.xml");
SetByJava demo = (SetByJava)app.getBean("text");
demo.doSomething();
app.close();
测试结果:
2.配置bean的时候指明初始跟销毁方法
如下:
public class SetByXml{
public void destroy() throws Exception {
System.out.println("destroy");
}
public void afterPropertiesSet() throws Exception {
System.out.println("init");
}
public void doSomething() {
System.out.println("doSomething");
}
}
配置bean:
<bean id="text2" class="InitAndDestroy.SetByXml" init-method="afterPropertiesSet" destroy-method="destroy">
</bean>
测试可得到同样的结果。
3、基于注解的配置
如下:
public class SetByAnno{
@PreDestroy
public void destroy() throws Exception {
System.out.println("destroy");
}
@PostConstruct
public void afterPropertiesSet() throws Exception {
System.out.println("init");
}
public void doSomething() {
System.out.println("doSomething");
}
}
配置bean:
<context:annotation-config />
<bean id="text3" class="InitAndDestroy.SetByAnno">
</bean>
测试可得到同样的结果。