Spring框架核心源代码的分析及其感受-IOC篇-3

在上一篇中,我们找到了doCreateBean方法,我绕了半圈才找到create bean的实际入口:

BeanWrapper instanceWrapper = null;
........
if (instanceWrapper == null) {
			//只创建Bean,但是没有注入
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
.......
///这就是依赖注入的方法
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
......
return exposedObject;

 

这里面有个BeanWrapper类型,实际上是createBeanInstance方法实例化我们get的Bean(createBeanInstance方法将创建对象的工作委托给了SimpleInstantiationStrategy类的instantiate方法,而instantiate方法调用了BeanUtils.instantiateClass(constructorToUse),下面是instantiateClass的实现:

public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
....
try {
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args);
}
.....
}

 看到了吧?其实就是反射直接通过构造函数实例化的!

这里的BeanWrapper其实是目标Bean的包装类,具体实现是BeanWrapperImpl。我们在下来看看populateBean方法的实现,其中有这样一段代码:

if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// Add property values based on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			// Add property values based on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

 

可以看到自动装备是这里处理的(自动装配先不讲,放到最后),另外还有这句话(populateBean调用applyPropertyValues):

applyPropertyValues(beanName, mbd, bw, pvs)

 

进到这个方法一看,它调用了BeanWrapperImpl的setPropertyValues来将根据BeanDedinition中记录的Property中的有关value和ref的值或者对象注入到目标对象中去.下一篇就是BeanWrapperImpl的实现!依赖注入的核心。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值