查看: 799|回复: 0

[Java学习] 浅谈Spring IoC容器的依赖注入原理

发表于 2018-4-15 08:00:01

本文介绍了浅谈Spring IoC容器的依赖注入原理,分享给大家,具体如下:

IoC容器初始化的过程,主要完成的工作是在IoC容器中建立 BeanDefinition 数据映射,并没有看到IoC容器对Bean依赖关系进行注入,

假设当前IoC容器已经载入用户定义的Bean信息,依赖注入主要发生在两个阶段

正常情况下,由用户第一次向IoC容器索要Bean时触发

但我们可以在 BeanDefinition 信息中通过控制 lazy-init 属性来让容器完成对Bean的预实例化,即在初始化的过程中就完成某些Bean的依赖注入的过程

1.getBean触发的依赖注入

在基本的IoC容器接口 BeanFactory 中,有一个 getBean 的接口定义,这个接口的实现就是触发依赖注入发生的地方.为了进一步了解这个依赖注入的过程,我们从 DefaultListableBeanFactory 的基类 AbstractBeanFactory 入手去看看getBean的实现

  1. // 这里是对 BeanFactory 接口的实现,比如getBean接口方法
  2. //这些getBean接口方法最终是通过调用doGetBean来实现的
  3. @Override
  4. public Object getBean(String name) throws BeansException {
  5. return doGetBean(name, null, null, false);
  6. }
  7. @Override
  8. public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
  9. return doGetBean(name, requiredType, null, false);
  10. }
  11. @Override
  12. public Object getBean(String name, Object... args) throws BeansException {
  13. return doGetBean(name, null, args, false);
  14. }
  15. public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
  16. return doGetBean(name, requiredType, args, false);
  17. }
  18. //这里是实际取得Bean的地方,也就是触发依赖注入发生的地方
  19. @SuppressWarnings("unchecked")
  20. protected <T> T doGetBean(
  21. final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
  22. throws BeansException {
  23. final String beanName = transformedBeanName(name);
  24. Object bean;
  25. // Eagerly check singleton cache for manually registered singletons.
  26. //急切地检查单例人士缓存手动注册的单例
  27. //先从缓存中取得Bean,处理那些已经被创建过的单例Bean,这种Bean不要重复创建
  28. Object sharedInstance = getSingleton(beanName);
  29. if (sharedInstance != null && args == null) {
  30. if (logger.isDebugEnabled()) {
  31. if (isSingletonCurrentlyInCreation(beanName)) {
  32. logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
  33. "' that is not fully initialized yet - a consequence of a circular reference");
  34. }
  35. else {
  36. logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
  37. }
  38. }
  39. //这里的getObjectForBeanInstance完成的是FactoryBean的相关处理,以取得FactoryBean的相关处理,以取得FactoryBean的生产结果,BeanFactory和FactoryBean的区别已在前面讲过,这个过程在后面还会详细地分析
  40. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  41. }
  42. else {
  43. // Fail if we're already creating this bean instance:
  44. // We're assumably within a circular reference.
  45. if (isPrototypeCurrentlyInCreation(beanName)) {
  46. throw new BeanCurrentlyInCreationException(beanName);
  47. }
  48. // // 检查IoC容器中的BeanDefinition是否存在,若在当前工厂不存在则去顺着双亲BeanFactory链一直向上找
  49. BeanFactory parentBeanFactory = getParentBeanFactory();
  50. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  51. // Not found -> check parent.
  52. String nameToLookup = originalBeanName(name);
  53. if (args != null) {
  54. // Delegation to parent with explicit args.
  55. return (T) parentBeanFactory.getBean(nameToLookup, args);
  56. }
  57. else {
  58. // No args -> delegate to standard getBean method.
  59. return parentBeanFactory.getBean(nameToLookup, requiredType);
  60. }
  61. }
  62. if (!typeCheckOnly) {
  63. markBeanAsCreated(beanName);
  64. }
  65. try {
  66. //根据Bean的名字取得BeanDefinition
  67. final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  68. checkMergedBeanDefinition(mbd, beanName, args);
  69. // Guarantee initialization of beans that the current bean depends on.
  70. //递归获得当前Bean依赖的所有Bean(如果有的话)
  71. String[] dependsOn = mbd.getDependsOn();
  72. if (dependsOn != null) {
  73. for (String dep : dependsOn) {
  74. if (isDependent(beanName, dep)) {
  75. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  76. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  77. }
  78. registerDependentBean(dep, beanName);
  79. getBean(dep);
  80. }
  81. }
  82. //通过调用createBean方法创建Singleton bean实例
  83. if (mbd.isSingleton()) {
  84. sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
  85. @Override
  86. public Object getObject() throws BeansException {
  87. try {
  88. return createBean(beanName, mbd, args);
  89. }
  90. catch (BeansException ex) {
  91. // Explicitly remove instance from singleton cache: It might have been put there
  92. // eagerly by the creation process, to allow for circular reference resolution.
  93. // Also remove any beans that received a temporary reference to the bean.
  94. destroySingleton(beanName);
  95. throw ex;
  96. }
  97. }
  98. });
  99. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  100. }
  101. //这里是创建prototype bean的地方
  102. else if (mbd.isPrototype()) {
  103. // It's a prototype -> create a new instance.
  104. Object prototypeInstance = null;
  105. try {
  106. beforePrototypeCreation(beanName);
  107. prototypeInstance = createBean(beanName, mbd, args);
  108. }
  109. finally {
  110. afterPrototypeCreation(beanName);
  111. }
  112. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  113. }
  114. else {
  115. String scopeName = mbd.getScope();
  116. final Scope scope = this.scopes.get(scopeName);
  117. if (scope == null) {
  118. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  119. }
  120. try {
  121. Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
  122. @Override
  123. public Object getObject() throws BeansException {
  124. beforePrototypeCreation(beanName);
  125. try {
  126. return createBean(beanName, mbd, args);
  127. }
  128. finally {
  129. afterPrototypeCreation(beanName);
  130. }
  131. }
  132. });
  133. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  134. }
  135. catch (IllegalStateException ex) {
  136. throw new BeanCreationException(beanName,
  137. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  138. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  139. ex);
  140. }
  141. }
  142. }
  143. catch (BeansException ex) {
  144. cleanupAfterBeanCreationFailure(beanName);
  145. throw ex;
  146. }
  147. }
  148. // Check if required type matches the type of the actual bean instance.
  149. // 这里对创建的Bean进行类型检查,如果没有问题,就返回这个新创建的Bean,这个Bean已经是包含了依赖关系的Bean
  150. if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
  151. try {
  152. return getTypeConverter().convertIfNecessary(bean, requiredType);
  153. }
  154. catch (TypeMismatchException ex) {
  155. if (logger.isDebugEnabled()) {
  156. logger.debug("Failed to convert bean '" + name + "' to required type '" +
  157. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  158. }
  159. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  160. }
  161. }
  162. return (T) bean;
  163. }
复制代码

依赖注入就是在这里被触发的.而依赖注入的发生是在容器中的BeanDefinition数据已经建立好的前提下进行的.虽然我们可以用最简单的方式来描述IoC容器,那就是视其为一个HashMap,但只能说这个HashMap是容器的最基本的数据结构,而不是IoC容器的全部.

关于这个依赖注入过程会在下面详解,图1.1可以看到依赖注入的大致过程.

图1.1 依赖注入的过程

getBean是依赖注入的起点,之后会调用AbstractAutowireCapableBeanFactory中的createBean来生产需要的Bean,还对Bean初始化进行了处理,比如实现了在BeanDefinition中的init-method属性定义,Bean后置处理器等.下面通过createBean代码了解这个过程

  1. @Override
  2. protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
  3. if (logger.isDebugEnabled()) {
  4. logger.debug("Creating instance of bean '" + beanName + "'");
  5. }
  6. RootBeanDefinition mbdToUse = mbd;
  7. // Make sure bean class is actually resolved at this point, and
  8. // clone the bean definition in case of a dynamically resolved Class
  9. // which cannot be stored in the shared merged bean definition.
  10. //这里判断需要创建的Bean是否可以被实例化,这个类是否可以通过类加载器来载入
  11. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  12. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  13. mbdToUse = new RootBeanDefinition(mbd);
  14. mbdToUse.setBeanClass(resolvedClass);
  15. }
  16. // Prepare method overrides.
  17. try {
  18. mbdToUse.prepareMethodOverrides();
  19. }
  20. catch (BeanDefinitionValidationException ex) {
  21. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  22. beanName, "Validation of method overrides failed", ex);
  23. }
  24. try {
  25. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  26. //如果Bean配置了PostProcessor,那么这里返回的是一个Proxy
  27. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  28. if (bean != null) {
  29. return bean;
  30. }
  31. }
  32. catch (Throwable ex) {
  33. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  34. "BeanPostProcessor before instantiation of bean failed", ex);
  35. }
  36. try {
  37. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  38. if (logger.isDebugEnabled()) {
  39. logger.debug("Finished creating instance of bean '" + beanName + "'");
  40. }
  41. return beanInstance;
  42. }
  43. catch (BeanCreationException ex) {
  44. // A previously detected exception with proper bean creation context already...
  45. throw ex;
  46. }
  47. catch (ImplicitlyAppearedSingletonException ex) {
  48. // An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry...
  49. throw ex;
  50. }
  51. catch (Throwable ex) {
  52. throw new BeanCreationException(
  53. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  54. }
  55. }
  56. //接着到doCreate中去看看Bean是怎样生成的
  57. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
  58. // Instantiate the bean.
  59. //用来持有创建出来的Bean对象
  60. BeanWrapper instanceWrapper = null;
  61. //如果是单例,则先把缓存中的同名Bean清除
  62. if (mbd.isSingleton()) {
  63. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  64. }
  65. //这里是创建Bean的地方,由createBeanInstance来完成
  66. if (instanceWrapper == null) {
  67. //根据指定bean使用对应的策略创建新的实例,如:工厂方法,构造函数自动注入,简单初始化
  68. instanceWrapper = createBeanInstance(beanName, mbd, args);
  69. }
  70. final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
  71. Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
  72. // Allow post-processors to modify the merged bean definition.
  73. synchronized (mbd.postProcessingLock) {
  74. if (!mbd.postProcessed) {
  75. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  76. mbd.postProcessed = true;
  77. }
  78. }
  79. // Eagerly cache singletons to be able to resolve circular references
  80. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  81. //是否需要提前曝光:单例&允许循环依赖&当前bean正在创建中,检测循环依赖
  82. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  83. isSingletonCurrentlyInCreation(beanName));
  84. if (earlySingletonExposure) {
  85. if (logger.isDebugEnabled()) {
  86. logger.debug("Eagerly caching bean '" + beanName +
  87. "' to allow for resolving potential circular references");
  88. }
  89. //为避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
  90. addSingletonFactory(beanName, new ObjectFactory<Object>() {
  91. @Override
  92. public Object getObject() throws BeansException {
  93. //对bean再次依赖引用,主要应用SMartInstantialiationAware BeanPostProcessor,
  94. //其中我们熟知的AOP就是在这里将advice动态织入bean中,若无则直接返回bean,不做任何处理
  95. return getEarlyBeanReference(beanName, mbd, bean);
  96. }
  97. });
  98. }
  99. // Initialize the bean instance.
  100. //这里是对Bean的初始化,依赖注入往往在这里发生,这个exposedObject在初始化处理完后悔返回作为依赖注入完成后的Bean
  101. Object exposedObject = bean;
  102. try {
  103. //对bean进行填充,将各个属性值注入,其中可能存在依赖于其他bean的属性,则会递归初始化依赖bean
  104. populateBean(beanName, mbd, instanceWrapper);
  105. if (exposedObject != null) {
  106. //调用初始化方法,比如init-method
  107. exposedObject = initializeBean(beanName, exposedObject, mbd);
  108. }
  109. }
  110. catch (Throwable ex) {
  111. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  112. throw (BeanCreationException) ex;
  113. }
  114. else {
  115. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  116. }
  117. }
  118. if (earlySingletonExposure) {
  119. Object earlySingletonReference = getSingleton(beanName, false);
  120. // earlySingletonReference 只有在检测到有循环依赖的情况下才会非空
  121. if (earlySingletonReference != null) {
  122. if (exposedObject == bean) {
  123. //如果exposedObject 没有在初始化方法中被改变,也就是没有被增强
  124. exposedObject = earlySingletonReference;
  125. }
  126. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  127. String[] dependentBeans = getDependentBeans(beanName);
  128. Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
  129. for (String dependentBean : dependentBeans) {
  130. //检测依赖
  131. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  132. actualDependentBeans.add(dependentBean);
  133. }
  134. }
  135. //因为bean创建后其所依赖的bean一定是已经创建的,actualDependentBeans非空则表示当前bean创建后其依赖的bean却没有全部创建完,也就是说存在循环依赖
  136. if (!actualDependentBeans.isEmpty()) {
  137. throw new BeanCurrentlyInCreationException(beanName,
  138. "Bean with name '" + beanName + "' has been injected into other beans [" +
  139. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  140. "] in its raw version as part of a circular reference, but has eventually been " +
  141. "wrapped. This means that said other beans do not use the final version of the " +
  142. "bean. This is often the result of over-eager type matching - consider using " +
  143. "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
  144. }
  145. }
  146. }
  147. }
  148. // Register bean as disposable.
  149. try {
  150. //根据scope注册bean
  151. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  152. }
  153. catch (BeanDefinitionValidationException ex) {
  154. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  155. }
  156. return exposedObject;
  157. }
复制代码

依赖注入其实包括两个主要过程

  1. 生产Bea所包含的Java对象
  2. Bean对象生成之后,把这些Bean对象的依赖关系设置好

我们从上可以看到与依赖注入关系特别密切的方法有

createBeanInstance
生成Bean包含的Java对象

populateBean.
处理对各种Bean对象的属性进行处理的过程(即依赖关系处理的过程)

先来看 createBeanInstance源码

  1. /**
  2. * Create a new instance for the specified bean, using an appropriate instantiation strategy:
  3. * factory method, constructor autowiring, or simple instantiation.
  4. * @param beanName the name of the bean
  5. * @param mbd the bean definition for the bean
  6. * @param args explicit arguments to use for constructor or factory method invocation
  7. * @return a BeanWrapper for the new instance
  8. */
  9. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
  10. // Make sure bean class is actually resolved at this point.
  11. // 确认需要创建的Bean实例的类可以实例化
  12. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  13. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
  14. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  15. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  16. }
  17. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  18. if (instanceSupplier != null) {
  19. return obtainFromSupplier(instanceSupplier, beanName);
  20. }
  21. //若工厂方法非空,则使用工厂方法策略对Bean进行实例化
  22. if (mbd.getFactoryMethodName() != null) {
  23. return instantiateUsingFactoryMethod(beanName, mbd, args);
  24. }
  25. // Shortcut when re-creating the same bean...
  26. boolean resolved = false;
  27. boolean autowireNecessary = false;
  28. if (args == null) {
  29. synchronized (mbd.constructorArgumentLock) {
  30. //一个类有多个构造函数,每个构造函数都有不同的参数,所以调用前需要先根据参数锁定构造函数或对应的工厂方法
  31. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  32. resolved = true;
  33. autowireNecessary = mbd.constructorArgumentsResolved;
  34. }
  35. }
  36. }
  37. //如果已经解析过则使用解析好的构造函数方法不需要再次锁定
  38. if (resolved) {
  39. if (autowireNecessary) {
  40. //构造函数自动注入
  41. return autowireConstructor(beanName, mbd, null, null);
  42. }
  43. else {
  44. //使用默认构造函数构造
  45. return instantiateBean(beanName, mbd);
  46. }
  47. }
  48. // Need to determine the constructor...
  49. // 使用构造函数对Bean进行实例化
  50. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  51. if (ctors != null ||
  52. mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
  53. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  54. return autowireConstructor(beanName, mbd, ctors, args);
  55. }
  56. // No special handling: simply use no-arg constructor.
  57. //使用默认的构造函数对Bean进行实例化
  58. return instantiateBean(beanName, mbd);
  59. }
  60. /**
  61. * Instantiate the given bean using its default constructor.
  62. * @param beanName the name of the bean
  63. * @param mbd the bean definition for the bean
  64. * @return a BeanWrapper for the new instance
  65. */
  66. //最常见的实例化过程instantiateBean
  67. protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
  68. //使用默认的实例化策略对Bean进行实例化,默认的实例化策略是
  69. //CglibSubclassingInstantiationStrategy,也就是使用CGLIB实例化Bean
  70. try {
  71. Object beanInstance;
  72. final BeanFactory parent = this;
  73. if (System.getSecurityManager() != null) {
  74. beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
  75. @Override
  76. public Object run() {
  77. return getInstantiationStrategy().instantiate(mbd, beanName, parent);
  78. }
  79. }, getAccessControlContext());
  80. }
  81. else {
  82. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
  83. }
  84. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  85. initBeanWrapper(bw);
  86. return bw;
  87. }
  88. catch (Throwable ex) {
  89. throw new BeanCreationException(
  90. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  91. }
  92. }
复制代码

这里使用了CGLIB对Bean进行实例化.CGLIB是一个字节码生成器的类库,它提供了一系列的API来提供生成和转换Java的字节码的功能.

在Spring AOP中也使用CGLIB对Java的字节码进行增强.在IoC容器中,要了解怎样使用CGLIB来生成Bean对象,需要看一下SimpleInstantiationStrategy类.它是Spring用来生成Bean对象的默认类,它提供了两种实例化Bean对象的方法

  1. 通过BeanUtils,使用了Java的反射功能
  2. 通过CGLIB来生成
  1. public class SimpleInstantiationStrategy implements InstantiationStrategy {
  2. @Override
  3. public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
  4. // Don't override the class with CGLIB if no overrides.
  5. if (bd.getMethodOverrides().isEmpty()) {
  6. //这里取得指定的构造器或者生成对象的工厂方法来对Bean进行实例化
  7. Constructor<?> constructorToUse;
  8. synchronized (bd.constructorArgumentLock) {
  9. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  10. if (constructorToUse == null) {
  11. final Class<?> clazz = bd.getBeanClass();
  12. if (clazz.isInterface()) {
  13. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  14. }
  15. try {
  16. if (System.getSecurityManager() != null) {
  17. constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
  18. @Override
  19. public Constructor<?> run() throws Exception {
  20. return clazz.getDeclaredConstructor((Class[]) null);
  21. }
  22. });
  23. }
  24. else {
  25. constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
  26. }
  27. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  28. }
  29. catch (Throwable ex) {
  30. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  31. }
  32. }
  33. }
  34. //通过BeanUtils进行实例化,这个BeanUtils的实例化通过Constructor来实例化Bean,在BeanUtils中可以看到具体的调用ctor.newInstance(args)
  35. return BeanUtils.instantiateClass(constructorToUse);
  36. }
  37. else {
  38. // 使用CGLIB来实例化对象
  39. return instantiateWithMethodInjection(bd, beanName, owner);
  40. }
  41. }
  42. }
复制代码

Bean之间依赖关系的处理

依赖关系处理的入口是前面提到的populateBean方法.由于其中涉及的面太多,在这里就不贴代码了.简要介绍一下依赖关系处理的流程:在populateBean方法中,

首先取得在BeanDefinition中设置的property值,然后开始依赖注入的过程。

首先处理autowire的注入,可以byName或者是byType,之后对属性进行注入。

接着需要对Bean Reference进行解析,在对ManageList、ManageSet、ManageMap等进行解析完之后,就已经为依赖注入准备好了条件,这是真正把Bean对象设置到它所依赖的另一个Bean属性中去的地方,其中处理的属性是各种各样的。

依赖注入发生在BeanWrapper的setPropertyValues中,具体的完成却是在BeanWrapper的子类BeanWrapperImpl中实现的,它会完成Bean的属性值的注入,其中包括对Array的注入、对List等集合类以及对非集合类的域进行注入。

进过一系列的注入,这样就完成了对各种Bean属性的依赖注入过程。

在Bean的创建和对象依赖注入的过程中,需要依据BeanDefinition中的信息来递归地完成依赖注入。

从前面的几个递归过程中可以看到,这些递归都是以getBean为入口的。

一个递归是在上下文体系中查找需要的Bean和创建Bean的递归调用;

另一个递归是在依赖注入时,通过递归调用容器的getBean方法,得到当前Bean的依赖Bean,同时也触发对依赖Bean的创建和注入。

在对Bean的属性进行依赖注入时,解析的过程也是一个递归的过程。这样,根据依赖关系,一层层地完成Bean的创建和注入,直到最后完成当前Bean的创建。有了这个顶层Bean的创建和对它属性依赖注入的完成,意味着和当前Bean相关的整个依赖链的注入液完成了。

在Bean创建和依赖注入完成以后,在IoC容器中建立起一系列依靠依赖关系联系起来的Bean,这个Bean已经不再是简单的Java对象了。该Bean系列以及Bean之间的依赖关系建立完成之后,通过IoC的相关接口方法,就可以非常方便地供上层应用使用了。

2. lazy-init属性和预实例化

在前面的refresh方法中,我们可以看到调用了finishBeanFactoryInitialization来对配置了lazy-init的Bean进行处理。

其实在这个方法中,封装了对lazy-init属性的处理,实际的处理是在DefaultListableBeanFactory这个基本容器的preInstantiateSingleton方法中完成的。该方法对单例Bean完成预实例化,这个预实例化的完成巧妙地委托给容器来实现。如果需要预实例化,那么就直接在这里采用getBean去触发依赖注入,与正常依赖注入的触发相比,只有触发的时间和场合不同。在这里,依赖注入发生在容器执行refresh的过程中,即IoC容器初始化的过程中,而不像一般的依赖注入一样发生在IoC容器初始化完成以后,第一次通过getBean想容器索要Bean的时候。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报