Spring源码阅读(二):DI实现原理

DI实现原理

首先明确一点,DI的过程是从getBean()开始的,因为Spring是懒加载的(lazy),也就是说,只有用到这个bean时,才会发生DI。

getBean()时,开始实例化,实例化分为两种:

  • 目标类配置了AOP,则实例化其代理类;
  • 目标类没有配置AOP,则实例化这个原生对象。

这里有一个实例化的策略类:SimpleInstantiationStrategy,用来决定要实例化的是代理类还是原生类。实例化之后会存储实例相关信息:scop,proxy,instance,封装为BeanWrapper(统一的一个对外访问对象的入口,保护原生对象,扩展一些功能,缓存一些配置信息),即实例化操作之后,我们最终得到的就是这个BeanWrapper对象

根据流程先手绘了DI的时序图,结合时序图来看:

DI时序图

ApplicationContext继承了ListableBeanFactory,ListableBeanFactory继承了BeanFactory,BeanFactory中有getBean()方法,AbstractBeanFactory类实现了getBean(),而getBean()调用了自身的doGetBean()方法,所以我们直接看AbstractBeanFactory的doGetBean()方法。

先看注释:

Return an instance, which may be shared or independent, of the specified bean.

返回指定bean的一个实例,该实例可以是共享的,也可以是独立的。
表示这是一个创建bean的方法(会先判断是否已经存在这个bean,如果没有则create)。在内部也确实有一个createBean()方法,进入createBean()方法,其中会有一个doCreateBean()方法,这是创建bean的入口。

/**
 * Actually create the specified bean. Pre-creation processing has already happened
 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
 * <p>Differentiates between default bean instantiation, use of a
 * factory method, and autowiring a constructor.
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @param args explicit arguments to use for constructor or factory method invocation
 * @return a new instance of the bean
 * @throws BeanCreationException if the bean could not be created
 * @see #instantiateBean
 * @see #instantiateUsingFactoryMethod
 * @see #autowireConstructor
 */
//真正创建Bean的方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {

   // Instantiate the bean.
   //封装被创建的Bean对象
   BeanWrapper instanceWrapper = null;
   if (mbd.isSingleton()) {
      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
   }
   if (instanceWrapper == null) {
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }
   final Object bean = instanceWrapper.getWrappedInstance();
   //获取实例化对象的类型
   Class<?> beanType = instanceWrapper.getWrappedClass();
   if (beanType != NullBean.class) {
      mbd.resolvedTargetType = beanType;
   }

   // Allow post-processors to modify the merged bean definition.
   //调用PostProcessor后置处理器
   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                  ""Post-processing of merged bean definition failed"", ex);
         }
         mbd.postProcessed = true;
      }
   }

   // Eagerly cache singletons to be able to resolve circular references
   // even when triggered by lifecycle interfaces like BeanFactoryAware.
   //向容器中缓存单例模式的Bean对象,以防循环引用
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      if (logger.isDebugEnabled()) {
         logger.debug(""Eagerly caching bean '"" + beanName +
               ""' to allow for resolving potential circular references"");
      }
      //这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }

   // Initialize the bean instance.
   //Bean对象的初始化,依赖注入在此触发
   //这个exposedObject在初始化完成之后返回作为依赖注入完成后的Bean
   Object exposedObject = bean;
   try {
      //将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象
      populateBean(beanName, mbd, instanceWrapper);
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
   catch (Throwable ex) {
      if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
         throw (BeanCreationException) ex;
      }
      else {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, ""Initialization of bean failed"", ex);
      }
   }

   if (earlySingletonExposure) {
      //获取指定名称的已注册的单例模式Bean对象
      Object earlySingletonReference = getSingleton(beanName, false);
      if (earlySingletonReference != null) {
         //根据名称获取的已注册的Bean和正在实例化的Bean是同一个
         if (exposedObject == bean) {
            exposedObject = earlySingletonReference;
         }
         //当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象
         else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
            String[] dependentBeans = getDependentBeans(beanName);
            Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
            for (String dependentBean : dependentBeans) {
               if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                  actualDependentBeans.add(dependentBean);
               }
            }
            if (!actualDependentBeans.isEmpty()) {
               throw new BeanCurrentlyInCreationException(beanName,
                     ""Bean with name '"" + beanName + ""' has been injected into other beans ["" +
                     StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                     ""] in its raw version as part of a circular reference, but has eventually been "" +
                     ""wrapped. This means that said other beans do not use the final version of the "" +
                     ""bean. This is often the result of over-eager type matching - consider using "" +
                     ""'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."");
            }
         }
      }
   }

   // Register bean as disposable.
   //注册
   try {
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
   }
   catch (BeanDefinitionValidationException ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, ""Invalid destruction signature"", ex);
   }

   return exposedObject;
}

首先,一开始定义的BeanWrapper就是Bean对象的封装,是Bean实例化后的结果。this.factoryBeanInstanceCache就是存放bean实例化的缓存(单例)。如果存在则先删除,不存在则创建。

这个方法里有两个主要的方法比较重要:createBeanInstance()负责bean实例化的创建,populateBean()负责依赖注入。

实例化

先来看createBeanInstance()方法:

/**
 * Create a new instance for the specified bean, using an appropriate instantiation strategy:
 * factory method, constructor autowiring, or simple instantiation.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @param args explicit arguments to use for constructor or factory method invocation
 * @return a BeanWrapper for the new instance
 * @see #obtainFromSupplier
 * @see #instantiateUsingFactoryMethod
 * @see #autowireConstructor
 * @see #instantiateBean
 */
//创建Bean的实例对象
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   // Make sure bean class is actually resolved at this point.
   //检查确认Bean是可实例化的
   Class<?> beanClass = resolveBeanClass(mbd, beanName);

   //使用工厂方法对Bean进行实例化
   if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
      throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            ""Bean class isn't public, and non-public access not allowed: "" + beanClass.getName());
   }

   Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
   if (instanceSupplier != null) {
      return obtainFromSupplier(instanceSupplier, beanName);
   }

   if (mbd.getFactoryMethodName() != null)  {
      //调用工厂方法实例化
      return instantiateUsingFactoryMethod(beanName, mbd, args);
   }

   // Shortcut when re-creating the same bean...
   //使用容器的自动装配方法进行实例化
   boolean resolved = false;
   boolean autowireNecessary = false;
   if (args == null) {
      synchronized (mbd.constructorArgumentLock) {
         if (mbd.resolvedConstructorOrFactoryMethod != null) {
            resolved = true;
            autowireNecessary = mbd.constructorArgumentsResolved;
         }
      }
   }
   if (resolved) {
      if (autowireNecessary) {
         //配置了自动装配属性,使用容器的自动装配实例化
         //容器的自动装配是根据参数类型匹配Bean的构造方法
         return autowireConstructor(beanName, mbd, null, null);
      }
      else {
         //使用默认的无参构造方法实例化
         return instantiateBean(beanName, mbd);
      }
   }

   // Need to determine the constructor...
   //使用Bean的构造方法进行实例化
   Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
   if (ctors != null ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
         mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
      //使用容器的自动装配特性,调用匹配的构造方法实例化
      return autowireConstructor(beanName, mbd, ctors, args);
   }

   // No special handling: simply use no-arg constructor.
   //使用默认的无参构造方法实例化
   return instantiateBean(beanName, mbd);
}

这个方法会调用instantiateBean()来初始化BeanWrapper

/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return a BeanWrapper for the new instance
 */
//使用默认的无参构造方法实例化Bean对象
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
   try {
      Object beanInstance;
      final BeanFactory parent = this;
      //获取系统的安全管理接口,JDK标准的安全管理API
      if (System.getSecurityManager() != null) {
         //这里是一个匿名内置类,根据实例化策略创建实例对象
         beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
               getInstantiationStrategy().instantiate(mbd, beanName, parent),
               getAccessControlContext());
      }
      else {
         //将实例化的对象封装起来
         beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
      }
      BeanWrapper bw = new BeanWrapperImpl(beanInstance);
      initBeanWrapper(bw);
      return bw;
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, ""Instantiation of bean failed"", ex);
   }
}

看注释:

Instantiate the given bean using its default constructor.

即:使用默认构造函数实例化给定的bean

看代码:

BeanWrapper bw = new BeanWrapperImpl(beanInstance);

我们所需要的BeanWrapper是对beanInstance的封装,而beanInstance来自于前一步的:

getInstantiationStrategy().instantiate(mbd, beanName, parent)

进入instantiate()方法看一下:

@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
   // Don't override the class with CGLIB if no overrides.
   //如果Bean定义中没有方法覆盖,则就不需要CGLIB父类类的方法
   if (!bd.hasMethodOverrides()) {
      Constructor<?> constructorToUse;
      synchronized (bd.constructorArgumentLock) {
         //获取对象的构造方法或工厂方法
         constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
         //如果没有构造方法且没有工厂方法
         if (constructorToUse == null) {
            //使用JDK的反射机制,判断要实例化的Bean是否是接口
            final Class<?> clazz = bd.getBeanClass();
            if (clazz.isInterface()) {
               throw new BeanInstantiationException(clazz, ""Specified class is an interface"");
            }
            try {
               if (System.getSecurityManager() != null) {
                  //这里是一个匿名内置类,使用反射机制获取Bean的构造方法
                  constructorToUse = AccessController.doPrivileged(
                        (PrivilegedExceptionAction<Constructor<?>>) () -> clazz.getDeclaredConstructor());
               }
               else {
                  constructorToUse = clazz.getDeclaredConstructor();
               }
               bd.resolvedConstructorOrFactoryMethod = constructorToUse;
            }
            catch (Throwable ex) {
               throw new BeanInstantiationException(clazz, ""No default constructor found"", ex);
            }
         }
      }
      //使用BeanUtils实例化,通过反射机制调用”构造方法.newInstance(arg)”来进行实例化
      return BeanUtils.instantiateClass(constructorToUse);
   }
   else {
      // Must generate CGLIB subclass.
      //使用CGLIB来实例化对象
      return instantiateWithMethodInjection(bd, beanName, owner);
   }
}

这个方法会调用BeanUtils.instantiateClass来实例化,而在这个工具方法中,有这样一句代码:

return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
      KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));

KotlinDelegate.instantiateClass(ctor, args)表示使用有参构造方法的方式创建,
ctor.newInstance(args))表示使用无参的构造方法创建。

综上:createBeanInstance()方法最终是使用反射后封装得到的BeanWrapper(无论有参还是无参),存放在AbstractAutowireCapableBeanFactoryfactoryBeanInstanceCache中(IoC的)。

  • beanDefinitionMap,是Map<String, BeanDefinition>类型,存储beanDefinition,即配置信息(beanDefinition是对bean的描述,即对bean的抽象,Spring容器启动的过程中,会将Bean解析成Spring内部的BeanDefinition结构后面对Bean的操作就直接对BeanDefinition进行);

  • factoryBeanObjectCache,是Map<String, Object>类型,存储原生bean,即反射创建出的实际的对象;

  • factoryBeanInstanceCache,存储BeanWrapper,即原生Bean的包装类(是对beanDefinition的加工,会先从beanDefinitionMap取到beanDefinition,获取Bean属性的配置信息,使用属性编辑器对这些配置信息进行转换得到Bean属性的值,最后对Bean通过反射机制设置属性值)。

依赖注入

再来看populateBean()方法,方法前面一段是拿到PropertyValues(BeanDefiniton的属性值)。

只有到最后:

if (pvs != null) {
   //对属性进行注入
   applyPropertyValues(beanName, mbd, bw, pvs);
}

判断若这个属性值不为空,则调用applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs)方法来对PropertyValues属性进行注入。

而在applyPropertyValues()方法中:

bw.setPropertyValues(new MutablePropertyValues(deepCopy));

这句代码进行了属性的注入,继续深入

setPropertyValues(pvs, false, false);

setPropertyValue(pv);

nestedPa.setPropertyValue(tokens, pv);

经过一系列set之后,我们来到了AbstractNestablePropertyAccessorsetPropertyValue()方法,这个方法实现了属性依赖注入功能。进入processLocalProperty()方法,可以看到有一步:

ph.setValue(valueToApply);

还是set方法,这是对PropertyHandler属性的设置,进入这个setValue():

try {
   AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
         writeMethod.invoke(getWrappedInstance(), value), acc);
}
catch (PrivilegedActionException ex) {
   throw ex.getException();
}
ReflectionUtils.makeAccessible(writeMethod);
writeMethod.invoke(getWrappedInstance(), value);

这里都是利用了反射,使用getWriteMethod()获取到setter方法,并利用invoke()来执行这个setter实现属性赋值(即属性的注入)。

文章已创建 17

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部