Spring中的InstantiationAwareBeanPostProcessor和BeanPostProcessor
InstantiationAwareBeanPostProcessor接口继承了BeanPostProcessor。
BeanPostProcessor接口中有2个方法
1.Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
2.Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
InstantiationAwareBeanPostProcessor中除了上述的两个方法外还有本身接口的方法
1.Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
2.boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
3.PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
throws BeansException;
从表面的意思理解InstantiationAwareBeanPostProcessor实例化前后的处理器,BeanPostProcessor中的方法是初始化类时候的处理器(实例化早于初始化)在spring中初始化指的一般是在调用init-method属性前后。
在AbstractAutowireCapableBeanFactory的createBean方法中
@Override
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// Make sure bean class is actually resolved at this point.
resolveBeanClass(mbd, beanName);
// Prepare method overrides.
try {
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
在resolveBeforeInstantiation方法中会运用实现了InstantiationAwareBeanPostProcessor接口的类实例化前调用postProcessBeforeInstantiation如果返回不为空就会执行所有实现了BeanPostProcessor类(包括实现了InstantiationAwareBeanPostProcessor的类)的postProcessAfterInitialization方法。
在doCreateBean方法中会调用populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw)该方法主要是用来属性填充的。在开始时会调用实现InstantiationAwareBeanPostProcessor接口类的postProcessAfterInstantiation。返回值还能控制下面是否进行下面的属性填充。没有返回的话后面还会调用postProcessPropertyValues方法
在init-method方法生效前后调用postProcessBeforeInitialization和postProcessAfterInitialization方法
可以看出spring会尽量保证postProcessAfterInitialization能够执行。