【spring】BeanPostProcessor简介

BeanPostProcessor的用途:
如果我们需要在spring容器完成bean的实例化、配置和初始化前后添加一些自己的处理逻辑,那么可以扩展一个BeanPostProcessor接口的实现,然 后注册到容器中。

BeanPostProcessor中的方法:
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

BeanPostProcessor的用法:
顾名思义postProcessBeforeInitialization方法会在bean初始化之前调用,比如会在一个实现了InitializingBean接口的afterPropertiesSet方法或者ini-method方法之前调用,而postProcessAfterInitialization会在bean初始化之后调用。我们来举一个具体的例子,首先创建一个实体User,这个是实体包含了    {}块、无参构造方法、afterPropertiesSet方法、ini方法,将User和一个BeanPostProcessor实现类配置到spring文件中后启动容器,方法执行的先后顺序如下
user's {} block.
user's constructor.
execute postProcessBeforeInitialization.
user's afterPropertiesSet method.
user's ini method.
execute postProcessAfterInitialization.


关于InstantiationAwareBeanPostProcessor:
InstantiationAwareBeanPostProcessor是BeanPostProcessor一个子接口,它与bean的实例化相关,它在BeanPostProcessor的基础上增加了如下几个方法:
Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)throws BeansException
顾名思义postProcessBeforeInstantiation会在bean的 实例化之前调用,postProcessAfterInstantiation、postProcessPropertyValues会在bean的 实例化之后调用,接着上面的例子把User和一个InstantiationAwareBeanPostProcessor的实现类配置到sprin文件中后启动容器,方法执行的先后顺序如下


execute postProcessBeforeInstantiation
user's {} block.
user's constructor.
execute postProcessAfterInstantiation
execute postProcessPropertyValues

execute postProcessBeforeInitialization
user's afterPropertiesSet method.
user's ini method.
execute postProcessAfterInitialization

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值