Customizing the Nature of a Bean
Spring Framework 提供了一堆api,去自定义加载bean时的行为
Lifecycle Callbacks
周期回调ApplicationContextAware and BeanNameAware
容器aware和 BeanNameAware其他 Aware Interfaces
aware指的是spring 自身框架的对外接口,提供和框架交互的
6.1 Lifecycle Callbacks
解释可以置入的点
和container的管理的bean 生命周期交互,你可以通过实现InitializingBean
和DisposableBean
接口。
容器调用afterPropertiesSet() 在初始化之前 和 destroy() 在摧毁之后,以让bean执行确定的动作
JSR-250的 @PostConstruct和 @PreDestroy是广泛使用的最佳时间。不想用 JSR-250,可以使用
init-method
和destroy-method
内部,spring框架使用BeanPostProcessor
的实现类去处理回调函数–他可以找到和调用合适 的方法。
如果你需要自定义其他行为,spring 默认不会提供,你可以实现BeanPostProcessor
类。
额外的,Spring 管理对象也可以通过实现Lifecyle
接口以让对象加入到启动和停止进程,被容器自己的声明周期地调用。
初始化Initialization Callbacks
该接口org.springframework.beans.factory.InitializingBean
让bean在设置完所有必要的properties后初始化。
接口就一个方法
我们不推荐使用该接口,因为冗余的代码。我们推荐使用@PostConstruct
。在xml 风格里 使用init-method
属性。对于java configuration, 你可以使用
@Bean
的initMethod
属性
示例1
示例2
示例1等于示例2,但是示例1就不会有冗余
销毁 Destruction Callbacks
通过实现org.springframework.beans.factory.DisposableBean
完成销毁前的动作。
接口有单一方法
同初始化,不推荐使用代码而是使用@PreDestroy
注解。inxml是destroy-method
属性。java configuration 是用@Bean
的destroyMethod
示例1