前言
接着上次的 Bean实例创建 继续学习,Bean已经创建完成之后就该填充属性了。
Bean 属性填充
接着 Bean 创建完之后,就该进行属性的填充了。
刚才创建的只是一个空壳,对象的字段还都没有被初始化,下一步就该进行字段的填充了。
具体截图如下,可以看到 createBeanInstance
方法执行完成后,bean 对象已经被创建,但是属性并没有被填充,还都是 null
,所以下一步就是**填充属性
**。
具体填充属性的地方: doCreateBean
方法中的 populateBean
方法。
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// 删除了大量代码,只保留了我需要看的逻辑
if (instanceWrapper == null) {
// 创建 bean 实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 填充属性
populateBean(beanName, mbd, instanceWrapper);
return exposedObject;
}
填充之前:
填充之后:
从 populateBean 开始,学习属性填充的细节
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 如果 BeanWrapper 为 null ,并且 RootBeanDefinition 还存在属性,则抛出异常,因为无法给空对象填充属性
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
// 没有属性,直接返回 跳过填充步骤
return;
}
}
// <1> 在设置属性之前给 InstantiationAwareBeanPostProcessors 一个改变 bean 的机会,其应用场景是 自定义的字段注入。
// 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.
// 判断 bean 是由应用程序本身定义,并且持有 InstantiationAwareBeanPostProcessors
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 遍历所有的 BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果类型是 InstantiationAwareBeanPostProcessor
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
// Bean 的所有属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// <2> 判断注入的类型
// AUTOWIRE_BY_NAME —— 根据名称自动注入
// AUTOWIRE_BY_TYPE —— 根据类型自动注入
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// MutablePropertyValues 允许对属性进行简单操作,并提供了构造函数支持 Map 的深度复制和构造
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 是否注册了 InstantiationAwareBeanPostProcessors
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
// <3> 遍历 BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
// 从 bw 对象中提取 PropertyDescriptor 结果集
// PropertyDescriptor ——> 通过一对存取方法提取一个属性
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// <4> 检查依赖
checkDependencies(beanName, mbd, filteredPds, pvs);
}
// <5> 将属性填充到 bean 中
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
填充完成之后,执行 BeanPostProcessor
可以看到,参照流程图,当 Spring 完成 Bean 的属性填充之后,就该执行 BeanPostProcessor:before
这一步了。
但是根据 BeanFactory 中提到的完整的生命周期:
在执行 BeanPostProcessor 之前要先实现 Aware
接口。
找出 Aware 所在代码位置
既然 BeanPostProcessor
之前需要实现 Aware
,那么就去代码中找到对应的位置。
而 Aware
的实现代码肯定位于 poupulateBean
之后,所以去看看紧跟着的 initializeBean
方法的源码:
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 这里是与 Aware 相关的源码 对应 BeanFactory 中 Bean 完整生命周期的 Step 10
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 这里来到了执行 BeanPostProcessorBefore 方法的地方,对应
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 初始化Bean
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// BeanpostProcessor:after 方法调用处
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
BeanPostProcessor:before
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 获取之前注册的所有 BeanPostProcessor , 然后循环调用 postProcessBeforeInitialization 方法对 Bean 做增强
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
Bean初始化
BeanPostProcessor:before
处理完,按流程该到对 Bean 初始化
了,于是去代码中找对应的实现:
initializeBean
方法 的第 22行 invokeInitMethods
就是对 Bean 进行初始化的逻辑,代码就在上面,这里就不重复了。
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
// 这里主要看看这个方法的注释:
// 设置所有 bean 的属性,如果 bean 实现了 InitializingBean 或定义了自定义的 init 方法,则执行回调
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
//...
}
BeanPostProcessor:after
Bean
初始化完成之后的代码就是调用 BeanPostProcessor:after
的地方,这几个逻辑离的非常近。
if (mbd == null || !mbd.isSynthetic()) {
// BeanpostProcessor:after 方法调用处
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
具体的代码逻辑和 before
一样,获取 BeanPostProcessor
集合,循环调用 postProcessAfterInitialization
方法。
整个 Bean 创建流程结束,对象返回
Q.E.D.
Comments | 0 条评论