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是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