Spring入门篇 学习笔记
定义 –> 初始化 –> 使用 –> 销毁
初始化
实现 org.springframework.beans.factory.InitializingBean 接口,覆盖 afterPropertiesSet 方法
1
2
3
4
5
6public class ExampleBean implements InitializingBean{
public void afterPropertiesSet() throws Exception{
// do some initialization work
}
}配置 init-method:
1
<bean id="exampleInitBean" class="example.ExampleBean" init-method="start"/>
1
2
3
4
5
6public class ExampleBean{
public void start(){
// do some initialization work
}
}
销毁
实现 org.springframework.beans.factory.DisposableBean 接口,覆盖 destory 方法
1
2
3
4
5
6public class ExampleBean implements DisposableBean{
public void destory() throws Exception{
// do some destruction work
}
}配置 destory-method
1
<bean id="exampleInitBean" class="example.ExampleBean" destory-method="stop"/>
1
2
3
4
5
6public class ExampleBean{
public void stop(){
// do some destruction work
}
}
配置全局默认初始化、销毁方法
1 | <?xml version="1.0" encoding="UTF-8"?> |
多种方式同时使用执行顺序
- afterPropertiesSet()
- init-method / default-init-method
- destory()
- destory-method / default-destory-method
- 如果同时配置了 init-method 和 default-init-method 或 destory-method 和 default-destory-method,default-init-method 或 default-destory-method 不执行
- default-init-method 和 default-destory-method 可以不在 Bean 中声明