spring 的 InitializingBean

本文详细解析了Spring框架中InitializingBean接口的作用与实现原理。该接口允许bean在所有属性设置完成后执行初始化操作,确保bean配置正确。AbstractAutowireCapableBeanFactory类中的invokeInitMethods方法会调用afterPropertiesSet,完成bean的最终初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

如果想在bean初始化的时候做一些操作,则可以继承自InitializingBean 接口;

 

这个接口只有一个方法就是afterPropertiesSet 作用就是当bean的各个属性初始化之后,会调用此方法

 

spring的具体实现是在AbstractAutowireCapableBeanFactory类中 invokeInitMethods方法会调用 afterPropertiesSet 

 

BeanNameAware 获得到容器中Bean的名称
BeanFactoryAware 获得当前bean Factory,从而调用容器的服务
ApplicationContextAware 当前的application context从而调用容器的服务
MessageSourceAware 得到message source从而得到文本信息
ApplicationEventPublisherAware 应用时间发布器,用于发布事件
ResourceLoaderAware 获取资源加载器,可以获得外部资源文件

 

转载于:https://www.cnblogs.com/liguangming/p/9645396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值