InitializingBean 介绍
InitializingBean 是 Spring 提供的一个接口,只包含一个方法 afterPropertiesSet()
。凡是实现了该接口的类,当其对应的 Bean 交由 Spring 管理后,当其必要的属性全部设置完成后,Spring 会调用该 Bean 的 afterPropertiesSet()
。
源码
/**
* Interface to be implemented by beans that need to react once all their
* properties have been set by a BeanFactory: for example, to perform custom
* initialization, or merely to check that all mandatory(强制的) properties have been set.
*
* <p>An alternative to implementing InitializingBean is specifying a custom
* init-method, for example in an XML bean definition.
* For a list of all bean lifecycle methods, see the BeanFactory javadocs.
*/
public interface InitializingBean {
/**
* Invoked by a BeanFactory after it has set all bean properties supplied
* (and satisfied BeanFactoryAware and ApplicationContextAware).
* <p>This method allows the bean instance to perform initialization only
* possible when all bean properties have been set and to throw an
* exception in the event of misconfiguration.
* @throws Exception in the event of misconfiguration (such
* as failure to set an essential property) or if initialization fails.
*/
void afterPropertiesSet() throws Exception;
}
示例
说明:示例使用 SpringBoot 环境。
@Component
public class InitializingBeanDemo implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("AfterPropertiesSet:Initializing");
}
}
// SpirngBoot Application
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
运行 main 函数启动项目,打印如下:
与init-method、@PostConstruct 比较
Spring 配置文件中还提供了 init-method 指定 init method,还有@PostConstruct 也提供了初始化方法,执行顺序如下:
构造器–》PostConstruct --》AfterPropertiesSet --》 Init
总结
- Spring 提供了两种初始化 Bean 的方式:实现 InitializingBean 接口,重写 afterPropertiesSet 方法;或者在配置文件中通过 init-method 属性指定初始化方法。
- 实现 InitializingBean 接口是直接调用 afterPropertiesSet 方法,比通过反射调用 init-method 指定的方法效率相对来说要高点。但是 init-method方式消除了对 Spring 的依赖。
- 如果同时指定了两种方法,如果调用 afterPropertiesSet 方法出错,则不会调用 init-method 指定的方法。