读书人

Spring框架核心源代码的分析及其体会-

发布时间: 2012-08-28 12:37:01 作者: rapoo

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的实现!依赖注入的核心。

?

读书人网 >软件架构设计

热点推荐