Initialization 回调
org.springframework.beans.factory.InitializingBean 接口允许 bean 在容器设置完所有属性后执行初始化工作,初始化工作在实现 InitializingBean 的类中的 afterPropertiesSet() 方法中执行。此外,初始化工作也可通过 @PostConstruct 注解来指定执行初始化工作的方法;或者指定一个 POJO 的初始化方法,然后在 XML 文件中使用 init-method 属性指定在该方法中执行初始化操作。
实现 InitializingBean 接口
|
|
|
|
使用 @PostConstruct 注解
|
|
使用 init-method 属性
|
|
|
|
Destroy 回调
org.springframework.beans.factory.DisposableBean 接口允许 bean 使用销毁回调,销毁工作在实现 DisposableBean 的类中的 destroy() 方法中执行。注解方法使用 @PreDestroy,XML 文件指定 destroy-method 属性即可。
实现 InitializingBean 接口
|
|
|
|
使用 @PostConstruct 注解
|
|
使用 init-method 属性
|
|
|
|
默认的 initialization 和 destroy 方法
当做 initialization 和 destroy 工作时,使用 init(), initialize(), dispose() 等类似的方法名有助于我们识别方法的作用。每次我们都需要为每个 bean 设置 init-method 或 destroy-method 属性指定生命周期的回调方法,有一个更加简便的方法,即在
|
|
default-destroy-method 属性的使用方法也和 default-init-method 一样。