InitializingBean, init-method 和 PostConstruct
1、概述
从接口的名字上不难发现,InitializingBean 的作用就是在 bean 初始化后执行定制化的操作。
Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:
- 通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
- 通过 <bean> 元素的 init-method/destroy-method 属性指定初始化之后 /销毁之前调用的操作方法;
- 在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。
2、InitializingBean vs init-method
接口定义如下:
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
接口只有一个方法afterPropertiesSet,
此方法的调用入口是负责加载 spring bean 的AbstractAutowireCapableBeanFactory,源码如下:
protected void invokeInitMethods(String beanName, Object bean,
RootBeanDefinition mbd) throws Throwable {
boolean isInitializingBean = bean instanceof InitializingBean;
if ((isInitializingBean)
&& (((mbd == null) || (!(mbd
.isExternallyManagedInitMethod("afterPropertiesSet")))))) {
if (this.logger.isDebugEnabled()) {
this.logger
.debug("Invoking afterPropertiesSet() on bean with name '"