1.InitializingBean接口:
Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory e.g. to perform custom initialization,or merely to check that all mandatory properties have been set.(由{@link BeanFactory}设置完所有属性后需要进行响应的bean所实现的接口:例如执行自定义初始化,或仅检查所有必需属性是否已设置。)
源码:
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
afterPropertiesSet()的执行时机?
Invoked by the containing {@code BeanFactory} after it has set all bean properties and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.(由包含的{@code BeanFactory}设置了所有bean属性并满足{@link BeanFactoryAware},{@ code ApplicationContextAware}等之后调用。)
总结:当创建一个bean并将该bean交给spring的ioc容器管理时,便会调用InitializingBean接口,在设置完bean的属性后调用afterPropertiesSet()做bean的参数检查以及在加入容器之前要做的一些准备工作。
2.DisposableBean接口:
Interface to be implemented by beans that want to release resources on destruction. A {@link BeanFactory} will invoke the destroy method on individual destruction of a scoped bean. An {@link org.springframework.context.ApplicationContext} is supposed to dispose all of its singletons on shutdown, driven by the application lifecycle.(要在销毁时释放资源的bean所实现的接口。{@link BeanFactory}将在单个销毁范围内的bean时调用destroy方法。假设{@link org.springframework.context.ApplicationContext}在应用程序生命周期的驱动下,在关机时处置其所有单例。)
源码:
public interface DisposableBean {
void destroy() throws Exception;
}
destroy()执行时机?
Invoked by the containing {@code BeanFactory} on destruction of a bean. @throws Exception in case of shutdown errors. Exceptions will get logged but not rethrown to allow other beans to release their resources as well.(由包含{@code BeanFactory}的销毁bean调用。@throws在关闭错误的情况下发生异常。异常将被记录,但不会被重新抛出以允许其他bean也释放其资源。)
在对象销毁的时候,会去调用DisposableBean
的destroy
方法。
同样,在对象销毁有一个参数配置destroy-method
,和init-method
相同,在调用销毁的时候,先执行 DisposableBean
的destroy
方法,后执行 destroy-method
声明的方法。
参考博客:https://www.jianshu.com/p/c2e33c451ee0