Spring中的InitializingBean与DisposableBean接口

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也释放其资源。)

在对象销毁的时候,会去调用DisposableBeandestroy方法。
同样,在对象销毁有一个参数配置destroy-method,和init-method相同,在调用销毁的时候,先执行 DisposableBeandestroy方法,后执行 destroy-method声明的方法。

参考博客:https://www.jianshu.com/p/c2e33c451ee0
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值