主要根据源码梳理下生命周期过程中的Bean后置处理器调用过程。包括BeanPostProcessor接口及其子接口(InstantiationAwareBeanPostProcessor、SmartInstantiationAwareBeanPostProcessor、MergedBeanDefinitionPostProcessor)的方法,贯穿整个Bean的实例化及初始化过程。
示例代码
import java.lang.reflect.Constructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;
@Component
public class BeanLifeCyclePostProcessor
implements MergedBeanDefinitionPostProcessor, SmartInstantiationAwareBeanPostProcessor {
private static final Logger _LOG = LoggerFactory.getLogger(BeanLifeCyclePostProcessor.class);
private static final String TEST_BEAN_NAME = "newsService";
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行MergedBeanDefinitionPostProcessor \n" + "=====的postProcessMergedBeanDefinition方法 \n"
+ "=====缓存注解信息");
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行InstantiationAwareBeanPostProcessor \n" + "=====的postProcessBeforeInstantiation方法 \n"
+ "=====得到bean实例前,返回代理,容器将实例化代理类");
return SmartInstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行InstantiationAwareBeanPostProcessor \n" + "=====的postProcessAfterInstantiation方法 \n"
+ "=====Bean已经实例化但spring还没有注入属性,判断Bean是否需要跳过属性填充返回True则跳过属性填充");
return SmartInstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行BeanPostProcessor \n" + "=====的postProcessBeforeInitialization方法 \n"
+ "=====Bean已经实例化执行初始化方法(init-method)前可以返回指定Bean的包装实例");
return MergedBeanDefinitionPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行BeanPostProcessor \n" + "=====的postProcessAfterInitialization方法 \n"
+ "=====Bean已经实例化执行初始化方法(init-method)后可以返回指定Bean的包装实例");
return MergedBeanDefinitionPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
@Override
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行SmartInstantiationAwareBeanPostProcessor \n" + "=====的determineCandidateConstructors方法 \n"
+ "=====Bean实例化之前,推断Bean的构造方法");
return SmartInstantiationAwareBeanPostProcessor.super.determineCandidateConstructors(beanClass, beanName);
}
@Override
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行SmartInstantiationAwareBeanPostProcessor \n" + "=====的getEarlyBeanReference方法 \n"
+ "=====Bean完全初始化之前,返回Bean的一个引用对象,通常用于解决循环依赖问题");
return SmartInstantiationAwareBeanPostProcessor.super.getEarlyBeanReference(bean, beanName);
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
if (TEST_BEAN_NAME.equals(beanName))
_LOG.info("=====执行InstantiationAwareBeanPostProcessor \n" + "=====的postProcessProperties方法 \n"
+ "=====Bean实例化后进行属性填充");
return SmartInstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
}
}
打印调用流程
2019-12-30 12:21:46.439 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行InstantiationAwareBeanPostProcessor
=====的postProcessBeforeInstantiation方法
=====得到bean实例前,返回代理,容器将实例化代理类
2019-12-30 12:21:46.547 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行SmartInstantiationAwareBeanPostProcessor
=====的determineCandidateConstructors方法
=====Bean实例化之前,推断Bean的构造方法
2019-12-30 12:21:46.548 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行MergedBeanDefinitionPostProcessor
=====的postProcessMergedBeanDefinition方法
=====缓存注解信息
2019-12-30 12:21:46.548 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行InstantiationAwareBeanPostProcessor
=====的postProcessAfterInstantiation方法
=====Bean已经实例化但spring还没有注入属性,判断Bean是否需要跳过属性填充返回True则跳过属性填充
2019-12-30 12:21:47.603 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行SmartInstantiationAwareBeanPostProcessor
=====的getEarlyBeanReference方法
=====Bean完全初始化之前,返回Bean的一个引用对象,通常用于解决循环依赖问题
2019-12-30 12:21:47.604 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行InstantiationAwareBeanPostProcessor
=====的postProcessProperties方法
=====Bean实例化后进行属性填充
2019-12-30 12:21:47.610 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行BeanPostProcessor
=====的postProcessBeforeInitialization方法
=====Bean已经实例化执行初始化方法(init-method)前可以返回指定Bean的包装实例
2019-12-30 12:21:47.610 INFO 10868 --- [ main] com.qqxhb.mybatis.config.BeanLifeCyclePostProcessor :
=====执行BeanPostProcessor
=====的postProcessAfterInitialization方法
=====Bean已经实例化执行初始化方法(init-method)后可以返回指定Bean的包装实例
从上面输入日志可以总结出后置处理器调用过程如下:
源码解析调用过程:(以下均为部分源码)
接口:InstantiationAwareBeanPostProcessor
方法1:postProcessBeforeInstantiation
得到bean实例前,返回代理,容器将实例化代理类
#1.org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[]);
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
try {
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
}
#2.org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(String, RootBeanDefinition);
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
#3.org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(Class<?>, String);
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
上面的方式,发现还是贴的代码太多,后面就只粘贴最后有个方法
接口:SmartInstantiationAwareBeanPostProcessor
方法2:determineCandidateConstructors
Bean实例化之前,推断Bean的构造方法
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(Class<?>, String)
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
接口:MergedBeanDefinitionPostProcessor
方法3:postProcessMergedBeanDefinition
解析并缓存注解信息(@Autowired @Qualifier @Value)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(RootBeanDefinition, Class<?>, String)
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
接口:InstantiationAwareBeanPostProcessor
方法4:postProcessAfterInstantiation
Bean已经实例化但spring还没有注入属性,判断Bean是否需要跳过属性填充返回True则跳过属性填充
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(String, RootBeanDefinition, BeanWrapper)
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
//后面代码省略
}
}
接口:SmartInstantiationAwareBeanPostProcessor
方法5:getEarlyBeanReference
Bean完全初始化之前,返回Bean的一个引用对象,通常用于解决 循 环 依 赖 \color{red}{循环依赖} 循环依赖问题
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getEarlyBeanReference(String, RootBeanDefinition, Object)
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
接口:InstantiationAwareBeanPostProcessor
方法6:postProcessProperties
Bean实例化后进行属性填充
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(String, RootBeanDefinition, BeanWrapper)
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
//省略代码
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
//省略代码
}
接口:BeanPostProcessor
方法7:postProcessBeforeInitialization
Bean已经实例化执行初始化方法(init-method) 前 \color{red}{前} 前 可以返回指定Bean的包装实例
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(String, Object, RootBeanDefinition)
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(Object, String)
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
接口:BeanPostProcessor
方法8:postProcessAfterInitialization
Bean已经实例化执行初始化方法(init-method) 后 \color{red}{后} 后 可以返回指定Bean的包装实例
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(String, RootBeanDefinition, Object[])
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(String, Object, RootBeanDefinition)
——> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(Object, String)
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}