1. To achieve InitializingBean, DisposableBean interfaces, override method
Specific achieve the following:
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");
}
}
Configuring bean
<bean id="text" class="InitAndDestroy.SetByJava">
</bean>
Test, instantiate ConfigurableApplicationContext, call the close method of simulation destroyed.
ConfigurableApplicationContext app = new ClassPathXmlApplicationContext("initText.xml");
SetByJava demo = (SetByJava)app.getBean("text");
demo.doSomething();
app.close();
Test results:
2. Configure the time specified in the original bean with methods of destruction
as follows:
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");
}
}
Configuration bean:
<bean id="text2" class="InitAndDestroy.SetByXml" init-method="afterPropertiesSet" destroy-method="destroy">
</bean>
The same test results obtained.
3, annotation-based configuration
as follows:
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");
}
}
Configuration bean:
<context:annotation-config />
<bean id="text3" class="InitAndDestroy.SetByAnno">
</bean>
The same test results obtained.