Spring源码分析——Bean属性填充
本篇文章讨论Spring源码中Bean生命周期中的属性填充过程和对属性中存在依赖引用的处理。
对应Github源码完整文档:https://github.com/TyCoding/mini-spring/tree/main/docs/ioc/03-bean-property-value
引言
在前面的章节中讲过了Bean实例化过程,在Bean通过BeanDefintion信息调用Cglib实例化Bean后,接着开始初始化Bean,再来整体下看Bean生命周期:

在之前我们知道BeanFactory接口的实现类AbstractBeanFactory实现了getBean()
逻辑,但实际上实例化的Bean的具体操作是由AbstractAutowireCapableBeanFactory类实现的,同样我们看下goCreateBean()
函数源码:
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
instanceWrapper = createBeanInstance(beanName, mbd, args);
// Allow post-processors to modify the merged bean definition.
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
......
// Initialize the bean instance.
Object exposedObject = bean;
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
......
// Register bean as disposable.
registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
}
// 属性填充
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
......
applyPropertyValues(beanName, mbd, bw, pvs);
......
}
applyPropertyValues
分析上面源码得知,populateBean()
函数主要负责属性填充,initializeBean()
函数主要负责一系列初始化函数的调用;而在populateBean()
函数中当获取到PropertyValues对象后,就交由applyPropertyValues
处理,看源码(AbstractAutowireCapableBeanFactory
类):
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
......
// Create a deep copy, resolving any references for values.
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
......
deepCopy.add(pv);
......
}
// Set our (possibly massaged) deep copy.
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
如上代码,稍微有点复杂(我这里简化了源码),核心逻辑就是循环PropertyValues对象,依次根据条件往List<PropertyValue> deepCopy
集合中写入最终要填充的属性信息;
注意: 从上面得知核心函数bw.setPropertyValues()
,其中的bw
是BeanWraper接口对象,而setPropertyValues()
函数来自PropertyAccessor接口,此函数的实现位于AbstractPropertyAccessor类。
其中setPropertyValues()
函数要创建MutablePropertyValues
对象。
setPropertyValues
根据上面的分析可能开始有点绕了,实际上在手写Spring项目:https://github.com/TyCoding/mini-spring 中我们把这一块的设计仅简单实现了,Spring源码中这些接口实现有些麻烦,我们从类图中分析:

PropertyAccessor接口定义如下:
+ getPropertyTypeDescriptor(String) TypeDescriptor?
+ getPropertyValue(String) Object?
+ getPropertyType(String) Class~?~?
+ setPropertyValues(Map~?, ?~) void
+ setPropertyValues(PropertyValues, boolean, boolean) void
+ isReadableProperty(String) boolean
+ isWritableProperty(String) boolean
+ setPropertyValue(PropertyValue) void
+ setPropertyValues(PropertyValues) void
+ setPropertyValues(PropertyValues, boolean) void
+ setPropertyValue(String, Object?) void
BeanWrapperImpl实现类定义如下:

属性填充
结合上面的源码分析,我们知道Spring属性填充涉及三个核心的类:BeanWrapperImpl、AbstractPropertyAccessor、MutablePropertyValues
-
首先AbstractAutowireCapableBeanFactory负责开始调用属性填充业务接口 -
Spring容器启动执行属性填充时从BeanDefinition中拿到所有的PropertyValues对象 -
PropertyValues属性信息最终会被设置到MutablePropertyValues对象中 -
然后BeanWrapperImpl最终拿到这些MutablePropertyValues对象循环调用反射设置属性值
Test
public class BeanPropertyTest {
@Test
public void t() {
// 创建一个MutablePropertyValues对象
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.add("name", "TyCoding");
propertyValues.add("age", 18);
// 创建一个Student Bean对象,并执行属性填充
Student bean = new Student();
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(bean);
beanWrapper.setPropertyValues(propertyValues);
// 输出设置后的Bean属性值
System.out.println("Name: " + bean.getName());
System.out.println("Age: " + bean.getAge());
}
}
class Student {
private String name;
private int age;
//getter/setter
}

如上在BeanWrapperImpl对象setValue()
函数设置断点即可看到Spring在利用反射通过setter函数设置属性值。
属性中存在依赖引用
上面我们仅仅说了对于普通类型属性,可以通过反射技术进行属性填充。但是如果属性中包含引用了其他Bean,则Spring需要先执行getBean
操作再将引用填充到属性值中。
同样,此操作发生在AbstractAutowireCapableBeanFactory类的populateBean()
函数中,源码如下:
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
......
// 处理涉及依赖引用的属性
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
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;
}
......
applyPropertyValues(beanName, mbd, bw, pvs);
}
接着看autowireByName()
函数:
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
registerDependentBean(propertyName, beanName);
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
此函数首先判断属性名是否是包含在beanMap缓存中,存在则先getBean()
,然后再填充依赖bean的引用。
注意: 此过程涉及三级缓存,Spring需要通过三级缓存处理循环依赖问题。
Spring源码专栏
此专栏将从Spring源码角度整体分析Spring设计思路以及常见的面试题。
配套作者的手写Spring的项目:https://github.com/TyCoding/mini-spring 。该项目中包含各个阶段的开发文档,有关Spring源码更详细的分析测试文档请查阅:https://github.com/TyCoding/mini-spring/tree/main/docs
联系我
-
个人博客:http://tycoding.cn/ -
GitHub:https://github.com/tycoding -
微信公众号:程序员涂陌 -
QQ交流群:866685601
原文始发于微信公众号(程序员涂陌):Spring源码分析——Bean属性填充
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/145614.html