初始化
1、实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法。
public class ExampleInitializingBean implements InitializingBean{
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");
}
}
2、配置init-method。(该类的bean中加上init-method属性,调用该类的init方法。若类中没有init方法将报错。)
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init">
public class ExampleBean {
public void init() {
System.out.println("start");
}
}
3、配置全局默认初始化方法
在xml开始的<beans>标签中加入default-init-method属性。需在类中有相应的init方法。若没有,不会报错,但不起效。
<beans xmlns="***" default-init-method="init" default-destroy-method="destroy">
销毁
1、实现org.springframework.beans.factory.DisposableBean接口,覆盖destroy方法。
public class ExampleDisposableBean implements DisposableBean{
@Override
public void destroy() throws Exception {
System.out.println("<span style="font-family: Arial, Helvetica, sans-serif;">destroy</span><span style="font-family: Arial, Helvetica, sans-serif;">");</span>
}
}
2、配置destroy-method。(该类的bean中加上destroy-method属性,调用该类的cleanup方法。若类中没有cleanup方法将报错。)
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="<span style="font-family: Arial, Helvetica, sans-serif;">cleanup</span><span style="font-family: Arial, Helvetica, sans-serif;">"></span>
public class ExampleBean {
public void cleanup() {
System.out.println("stop");
}
}
在xml开始的<beans>标签中加入default-destroy-method属性。需在类中有相应的destroy方法。若没有,不会报错,但不起效。
<beans xmlns="***" default-init-method="init" default-destroy-method="destroy">
总结:
若同时有默认的初始化/销毁方式和bean中的初始化/销毁方式,则默认方式不起效。