Spring框架探索三(Bean的注入)

​ 一、Spring注入流程如下所示。

在这里插入图片描述

二、注入流程具体代码

finishBeanFactoryInitialization自动注入Bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   // 将conversionservice实例化并加入到工厂
   if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
         beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      beanFactory.setConversionService(
            beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
   }

   // 加入valueResolver
   if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver(strVal -> 											getEnvironment().resolvePlaceholders(strVal));
   }

   // weaverAwareNames的实例化
   String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, 			false, false);
   for (String weaverAwareName : weaverAwareNames) {
      getBean(weaverAwareName);
   }

   // 临时类加载器设置为null
   beanFactory.setTempClassLoader(null);

   // Allow for caching all bean definition metadata, not expecting further changes.
   beanFactory.freezeConfiguration();

   // 所有剩余的BeanDefine的实例化
   beanFactory.preInstantiateSingletons();
}

​ preInstantiateSingletons剩余BeanDefinition的实例化

public void preInstantiateSingletons() throws BeansException {
   if (logger.isTraceEnabled()) {
      .... // 日志
   }

   // 获取所有的Bean
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

   // 循环实例化
   for (String beanName : beanNames) {
      // 获取RootBeanDefinition
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
         if (isFactoryBean(beanName)) {
           	// 以工厂类工厂类的形式实例化类
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
            if (bean instanceof FactoryBean) {
               FactoryBean<?> factory = (FactoryBean<?>) bean;
               boolean isEagerInit;
               // 判断是否允许立即加载类
               if (System.getSecurityManager() != null && factory instanceof 							SmartFactoryBean) {
                  isEagerInit = AccessController.doPrivileged(
                      (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) 									factory)::isEagerInit, getAccessControlContext());
               }
               else {
                  isEagerInit = (factory instanceof SmartFactoryBean &&
                        ((SmartFactoryBean<?>) factory).isEagerInit());
               }
               if (isEagerInit) {
                  // 实例化
                  getBean(beanName);
               }
            }
         }
         else {
            // 实例化
            getBean(beanName);
         }
      }
   }

   // 对Bean循环注入
   for (String beanName : beanNames) {
      // 获取单例,循环依赖处理。从三级缓存中尝试获取
      Object singletonInstance = getSingleton(beanName);
      // 实例化后置处理器,获取实例后调用。
      if (singletonInstance instanceof SmartInitializingSingleton) {
         SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) 					singletonInstance;
         if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }
         else {
            smartSingleton.afterSingletonsInstantiated();
         }
      }
   }
}

​ getMergedLocalBeanDefinition获取RootBeanDefinition。

protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws 			BeansException {
   // 是否创建过mergedBeanDefinitions中获取RootBeanDefinition,有直接返回
   RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
   if (mbd != null && !mbd.stale) {
      return mbd;
   }
   return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}

protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
	throws BeanDefinitionStoreException {
		return getMergedBeanDefinition(beanName, bd, null);
}
	
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd, 	@Nullable BeanDefinition containingBd) throws BeanDefinitionStoreException {
	// 加锁保证只能创建一个RootBeanDefinition
	synchronized (this.mergedBeanDefinitions) {
		RootBeanDefinition mbd = null;
		RootBeanDefinition previous = null;

		// 判断是否已经创建过
		if (containingBd == null) {
			mbd = this.mergedBeanDefinitions.get(beanName);
		}

		if (mbd == null || mbd.stale) {
			previous = mbd;
			if (bd.getParentName() == null) {
				// 拷贝RootBeanDefinition
				if (bd instanceof RootBeanDefinition) {
					mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
				}
				else {
                   	  // 新建RootBeanDefinition
					mbd = new RootBeanDefinition(bd);
				}
			}
			else {
				
				BeanDefinition pbd;
				try {
					String parentBeanName = transformedBeanName(bd.getParentName());
					if (!beanName.equals(parentBeanName)) {
						pbd = getMergedBeanDefinition(parentBeanName);
					}
					else {
						BeanFactory parent = getParentBeanFactory();
						if (parent instanceof ConfigurableBeanFactory) {
							pbd = ((ConfigurableBeanFactory) 													parent).getMergedBeanDefinition(parentBeanName);
						}
						else {
							.... //异常
						}
					}
				}
				catch (NoSuchBeanDefinitionException ex) {
					.... //异常
				}
				// 新建RootBeanDefinition
				mbd = new RootBeanDefinition(pbd);
              	 // 使用bd进行属性覆盖
				mbd.overrideFrom(bd);
			}

			// 设置作用域
			if (!StringUtils.hasLength(mbd.getScope())) {
				mbd.setScope(SCOPE_SINGLETON);
			}

			// 设置作用域
			if (containingBd != null && !containingBd.isSingleton() && 									mbd.isSingleton()) {
              		mbd.setScope(containingBd.getScope());
			}

			// 加入到mergedBeanDefinitions
			if (containingBd == null && isCacheBeanMetadata()) {
				this.mergedBeanDefinitions.put(beanName, mbd);
			}
		}
		if (previous != null) {
			copyRelevantMergedBeanDefinitionCaches(previous, mbd);
		}
		return mbd;
	}
}

​ getBean自动生成Bean入口

public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}

protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] 		args, boolean typeCheckOnly) throws BeansException {

  	// beanName的处理,别名和工厂Bean的处理
	String beanName = transformedBeanName(name);
	Object bean;

	// 三级缓存中获取Bean,解决循环引用问题
	Object sharedInstance = getSingleton(beanName);
	if (sharedInstance != null && args == null) {
		if (logger.isTraceEnabled()) {
          	 // 判断是否是正在创建的单例实例 
			if (isSingletonCurrentlyInCreation(beanName)) {
				.... // 日志
			}
			else {
				logger.trace("Returning cached instance of singleton bean '" + 								beanName + "'");
			}
		}
      	 // 三级缓存中获取实例
		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
	}
	else {
		// 判断是否在正在创建多实例集合中,直接报错是因为多实例不能解决循环引用问题
		if (isPrototypeCurrentlyInCreation(beanName)) {
			.... //异常
		}

		// 获取父BeanFactory 
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// 名称处理--工厂类以&开头,别名
			String nameToLookup = originalBeanName(name);
			if (parentBeanFactory instanceof AbstractBeanFactory) {
              	 // 创建Bean
				return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
						nameToLookup, requiredType, args, typeCheckOnly);
			}
			else if (args != null) {
				// 父工厂获取Bean
				return (T) parentBeanFactory.getBean(nameToLookup, args);
			}
			else if (requiredType != null) {
				// 父工厂获取Bean
				return parentBeanFactory.getBean(nameToLookup, requiredType);
			}
			else {
              	 // 父工厂获取Bean
				return (T) parentBeanFactory.getBean(nameToLookup);
			}
		}

		if (!typeCheckOnly) {
          	 // 标记为已经创建
			markBeanAsCreated(beanName);
		}
		try {
          	 // 获取RootBeanDefinition
			RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
			checkMergedBeanDefinition(mbd, beanName, args);

			// 获取dependsOn,对应DependsOn注解
			String[] dependsOn = mbd.getDependsOn();
			if (dependsOn != null) {
				for (String dep : dependsOn) {
					if (isDependent(beanName, dep)) {
						.... //异常
					}
                  	  // 注册以来的Bean
					registerDependentBean(dep, beanName);
					try {
                      	  // 生成以来的Bean
						getBean(dep);
					}
					catch (NoSuchBeanDefinitionException ex) {
						.... //异常
						}
					}
				}

				// 获取实例
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) { 
							destroySingleton(beanName);
								.... //异常
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
          		 // 判断是否是多实例
				else if (mbd.isPrototype()) {
					
					Object prototypeInstance = null;
					try {
                          // 多实例Bean注入前处理
						beforePrototypeCreation(beanName);
                      	  // 多实例Bean生成
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
                      	  // 多实例Bean注入后处理
						afterPrototypeCreation(beanName);
					}
                  	 // 对生成类型进行判断
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, 							mbd);
				}
 				else {
                  	  // 获取作用域名称
					String scopeName = mbd.getScope();
					if (!StringUtils.hasLength(scopeName)) {
						.... //异常
					}
					Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						.... //异常
					}
					try {
						Object scopedInstance = scope.get(beanName, () -> {
                          	  // 多实例Bean注入前处理
							beforePrototypeCreation(beanName);
							try {
                              	   // 多实例Bean生成
								return createBean(beanName, mbd, args);
							}
							finally {
                              	   // 多实例Bean注入后处理
								afterPrototypeCreation(beanName);
							}
						});
                      	  // 对生成类型进行判断
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, 							mbd);
					}
					catch (IllegalStateException ex) {
						.... //异常
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				.... //异常
			}
		}

		// 如果requiredType不为空,且和生成的Bean类型不同。需要进行类型转换
		if (requiredType != null && !requiredType.isInstance(bean)) {
			try {
              	 // 获取类型转换的类并进行类型装欢,即是之前注入的ConversionService,或者该类实				  // 现类PropertyEditorRegistrySupport,则作为类型转换类加入到							// ConversionService
				T convertedBean = getTypeConverter().convertIfNecessary(bean, 								requiredType);
				if (convertedBean == null) {
					.... // 异常
				}
               	 // 返回转换后的类型
				return convertedBean;
			}
			catch (TypeMismatchException ex) {
				if (logger.isTraceEnabled()) {
					.... // 日志
				}
				.... //异常
			}
		}
	return (T) bean;
}

​ canonicalName、transformedBeanName类名转换,解决&前缀问题和别名问题。

public String canonicalName(String name) {
	String canonicalName = name;
	// 别名处理
	String resolvedName;
	do {
		resolvedName = this.aliasMap.get(canonicalName);
		if (resolvedName != null) {
			canonicalName = resolvedName;
		}
	}
	while (resolvedName != null);
	return canonicalName;
}
// 以&前缀的类进行处理
public static String transformedBeanName(String name) {
   Assert.notNull(name, "'name' must not be null");
   if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
      return name;
   }
   return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
      do {
         // 去除前缀
         beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
      }
      while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
      return beanName;
   });
}

​ getSingleton三级缓存获取单例,解决循环依赖问题。

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
   // singletonObjects已创建集合获取单例
   Object singletonObject = this.singletonObjects.get(beanName);
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      // 早期单例集合earlySingletonObjects获取创建中的实例
      singletonObject = this.earlySingletonObjects.get(beanName);
      if (singletonObject == null && allowEarlyReference) {
         synchronized (this.singletonObjects) {
            // 枷锁后再次判断,解决加锁过程中创建实例额外难题
            singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
               singletonObject = this.earlySingletonObjects.get(beanName);
               if (singletonObject == null) {
                  ObjectFactory<?> singletonFactory = 													this.singletonFactories.get(beanName);
                  if (singletonFactory != null) {
                     // 获取单例,并将工厂中的实例移动到早期实例集合中
                     singletonObject = singletonFactory.getObject();
                     this.earlySingletonObjects.put(beanName, singletonObject);
                     this.singletonFactories.remove(beanName);
                  }
               }
            }
         }
      }
   }
   return singletonObject;
}

​ 创建Bean

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] 	args) throws BeanCreationException {

   if (logger.isTraceEnabled()) {
      .... // 日志
   }
   RootBeanDefinition mbdToUse = mbd;

   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      mbdToUse = new RootBeanDefinition(mbd);
      mbdToUse.setBeanClass(resolvedClass);
   }

   // replaced-method和lookup-method会存在overrideMethod属性,获取需要的方法
   try {
      mbdToUse.prepareMethodOverrides();
   }
   catch (BeanDefinitionValidationException ex) {
      .... //异常
   }

   try {
      // Bean实例获取前处理
      Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      if (bean != null) {
         return bean;
      }
   }
   catch (Throwable ex) {
            .... //异常
   }

   try {
      // doCreateBean创建实例
      Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      if (logger.isTraceEnabled()) {
         .... // 日志
      }
      return beanInstance;
   }
   catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
      .... //异常
   }
   catch (Throwable ex) {
      .... //异常
   }
}

​ resolveBeforeInstantiation实例化前处理,对自定义的targetClass进行代理。

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
   Object bean = null;
   if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
      // 实例化之前处理,最后的机会给实例创建代理类(自定义的TargetSource)
      if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
         Class<?> targetType = determineTargetType(beanName, mbd);
         if (targetType != null) {
            // 实例化前后置处理,创建代理类---后置处理器一
            bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
            if (bean != null) {
               // 实例化后处理---后置处理器二
               bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
            }
         }
      }
      mbd.beforeInstantiationResolved = (bean != null);
   }
   return bean;
}
后置处理器一、postProcessBeforeInstantiation对包含自定义targetSourced的类创建代理
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
   Object cacheKey = getCacheKey(beanClass, beanName);

   if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
      if (this.advisedBeans.containsKey(cacheKey)) {
         return null;
      }
      if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
         this.advisedBeans.put(cacheKey, Boolean.FALSE);
         return null;
      }
   }

   // 获取自定义targetSourced
   TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
   if (targetSource != null) {
      if (StringUtils.hasLength(beanName)) {
         this.targetSourcedBeans.add(beanName);
      }
      // 获取Advisor数组
      Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, 		targetSource);
      // 创建代理类
      Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
      this.proxyTypes.put(cacheKey, proxy.getClass());
      return proxy;
   }

   return null;
}

​ 后置处理器二、applyBeanPostProcessorsAfterInitialization初始化后处理

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String 		beanName) throws BeansException {
   Object result = existingBean;
   for (BeanPostProcessor processor : getBeanPostProcessors()) {
  		Object current = processor.postProcessAfterInitialization(result, beanName);
  		if (current == null) {
     		return result;
  		}
  		result = current;
    }
   return result;
}

​ postProcessAfterInitialization具体处理过程,会根据需要生成具体的代理类,跟getEarlyBeanReference处理方式一致。

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
 	if (bean != null) {
  		Object cacheKey = getCacheKey(bean.getClass(), beanName);
  		if (this.earlyProxyReferences.remove(cacheKey) != bean) {
     		return wrapIfNecessary(bean, beanName, cacheKey);
  		}
	}
   return bean;
}
doCreateBean创建实例
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] 	args) throws BeanCreationException {

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

   synchronized (mbd.postProcessingLock) {
      if (!mbd.postProcessed) {
         try {
            // 实例化后初始化之前处理---后置处理器四
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
         }
         catch (Throwable ex) {
            .... //异常
         }
         mbd.postProcessed = true;
      }
   }

   // 是否早期暴露,单例、允许循环依赖且在创建中会早期暴露
   boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
         isSingletonCurrentlyInCreation(beanName));
   if (earlySingletonExposure) {
      if (logger.isTraceEnabled()) {
         .... // 日志
      }
      // 加入到三级缓存,getEarlyBeanReference会判断是否需要获取代理类。然后将其加入到三级缓存
      // 内部会调用后置处理器---后置处理器五
      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
   }

   // bean赋值给暴露的实体类
   Object exposedObject = bean;
   try {
      // 属性注入
      populateBean(beanName, mbd, instanceWrapper);
      // 初始化处理,处理类的初始化方法
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
   catch (Throwable ex) {
      if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) 			ex).getBeanName())) {
         .... //异常
      }
      else {
         .... //异常
      }
   }

   // 早期暴露
   if (earlySingletonExposure) {
      // 三级缓存取对象实例
      Object earlySingletonReference = getSingleton(beanName, false);
      if (earlySingletonReference != null) {
         if (exposedObject == bean) {
            exposedObject = earlySingletonReference;
         }
         else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
            // 获取以来的Bean
            String[] dependentBeans = getDependentBeans(beanName);
            Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
            for (String dependentBean : dependentBeans) {
               if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                  actualDependentBeans.add(dependentBean);
               }
            }
            if (!actualDependentBeans.isEmpty()) {
                .... //异常
            }
         }
      }
   }

   try {
      registerDisposableBeanIfNecessary(beanName, bean, mbd);
   }
   catch (BeanDefinitionValidationException ex) {
      .... //异常
   }

   return exposedObject;
}

​ createBeanInstance创建对象实例。

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
   // Make sure bean class is actually resolved at this point.
   Class<?> beanClass = resolveBeanClass(mbd, beanName);

   if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && 				!mbd.isNonPublicAccessAllowed()) {
        .... //异常
   }
   // 对于存在Supplier回调的,使用Supplier回调初始化
   Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
   if (instanceSupplier != null) {
      return obtainFromSupplier(instanceSupplier, beanName);
   }

   // 对于存在工厂方法的使用工厂方法进行初始化
   if (mbd.getFactoryMethodName() != null) {
      return instantiateUsingFactoryMethod(beanName, mbd, args);
   }

   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) {
         // 构造函数自动注入
         return autowireConstructor(beanName, mbd, null, null);
      }
      else {
         // 默认构造方法初始化
         return instantiateBean(beanName, mbd);
      }
   }

   // 构造函数后置处理器,处理Lookup标签和构造函数的处理----后置处理器三
   Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, 				beanName);
   if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
         mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      return autowireConstructor(beanName, mbd, ctors, args);
   }

   ctors = mbd.getPreferredConstructors();
   if (ctors != null) {
      // 自动装配初始化
      return autowireConstructor(beanName, mbd, ctors, null);
   }

   // 默认构造函数初始化
   return instantiateBean(beanName, mbd);
}

​ 后置处理器三、determineConstructorsFromBeanPostProcessors

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> 	beanClass, String beanName) throws BeansException {

   if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
            SmartInstantiationAwareBeanPostProcessor ibp = 												(SmartInstantiationAwareBeanPostProcessor) bp;
            Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, 						beanName);
            if (ctors != null) {
               return ctors;
            }
         }
      }
   }
   return null;
}

​ determineCandidateConstructors对构造函数进行处理

public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String 	beanName)throws BeanCreationException {

   // 判断Lookup注解是否存在,存在使用代理替换
   if (!this.lookupMethodsChecked.contains(beanName)) {
      if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
         try {
            Class<?> targetClass = beanClass;
            do {
               ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                  // 判断Lookup注解是否存在
                  Lookup lookup = method.getAnnotation(Lookup.class);
                  if (lookup != null) {
                     Assert.state(this.beanFactory != null, "No BeanFactory available");
                     LookupOverride override = new LookupOverride(method, lookup.value());
                     try {
                        RootBeanDefinition mbd = (RootBeanDefinition)
                              this.beanFactory.getMergedBeanDefinition(beanName);
                        // Bean定义加入MethodOverrides属性
                        mbd.getMethodOverrides().addOverride(override);
                     }
                     catch (NoSuchBeanDefinitionException ex) {
                        .... //异常
                     }
                  }
               });
               targetClass = targetClass.getSuperclass();
            }
            while (targetClass != null && targetClass != Object.class);

         }
         catch (IllegalStateException ex) {
            .... //异常
         }
      }
      this.lookupMethodsChecked.add(beanName);
   }

   // 缓存中取构造方阿飞
   Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
   if (candidateConstructors == null) {
      // Fully synchronized resolution now...
      synchronized (this.candidateConstructorsCache) {
         candidateConstructors = this.candidateConstructorsCache.get(beanClass);
         if (candidateConstructors == null) {
            Constructor<?>[] rawCandidates;
            try {
               rawCandidates = beanClass.getDeclaredConstructors();
            }
            catch (Throwable ex) {
               .... //异常
            }
            List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
            Constructor<?> requiredConstructor = null;
            Constructor<?> defaultConstructor = null;
            Constructor<?> primaryConstructor = 													BeanUtils.findPrimaryConstructor(beanClass);
            int nonSyntheticConstructors = 0;
            for (Constructor<?> candidate : rawCandidates) {
               if (!candidate.isSynthetic()) {
                  nonSyntheticConstructors++;
               }
               else if (primaryConstructor != null) {
                  continue;
               }
               MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
               if (ann == null) {
                  Class<?> userClass = ClassUtils.getUserClass(beanClass);
                  if (userClass != beanClass) {
                     try {
                        Constructor<?> superCtor =
                           userClass.getDeclaredConstructor(candidate.getParameterTypes());
                        ann = findAutowiredAnnotation(superCtor);
                     }
                     catch (NoSuchMethodException ex) {
                        .... //异常
                     }
                  }
               }
               if (ann != null) {
                  if (requiredConstructor != null) {
                     .... //异常
                  }
                  boolean required = determineRequiredStatus(ann);
                  if (required) {
                     if (!candidates.isEmpty()) {
                        .... //异常
                     }
                     requiredConstructor = candidate;
                  }
                  candidates.add(candidate);
               }
               else if (candidate.getParameterCount() == 0) {
                  defaultConstructor = candidate;
               }
            }
            if (!candidates.isEmpty()) {
               // Add default constructor to list of optional constructors, as fallback.
               if (requiredConstructor == null) {
                  if (defaultConstructor != null) {
                     candidates.add(defaultConstructor);
                  }
                  else if (candidates.size() == 1 && logger.isInfoEnabled()) {
                     .... //日志打印
                  }
               }
               candidateConstructors = candidates.toArray(new Constructor<?>[0]);
            }
            else if (rawCandidates.length == 1 && 
                     rawCandidates[0].getParameterCount() > 0) {
               candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
            }
            else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
            	defaultConstructor != null && 														!primaryConstructor.equals(defaultConstructor)) {
               candidateConstructors = 
                 new Constructor<?>[] {primaryConstructor, defaultConstructor};
            }
            else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
               candidateConstructors = new Constructor<?>[] {primaryConstructor};
            }
            else {
               candidateConstructors = new Constructor<?>[0];
            }
            this.candidateConstructorsCache.put(beanClass, candidateConstructors);
         }
      }
   }
   return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

​ 后置处理器四、applyMergedBeanDefinitionPostProcessors

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof MergedBeanDefinitionPostProcessor) {
         MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
         bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
      }
   }
}

public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		if (ApplicationListener.class.isAssignableFrom(beanType)) {
			this.singletonNames.put(beanName, beanDefinition.isSingleton());
		}
}

​ 查找@Autowired和@Value注解修饰的属性,加入到injectionMetadataCache和checkedElements。后面进行注入时注入的即是这里集合的属性。

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable 	PropertyValues pvs) {
	// 获取缓存中的key
	String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
	// 查看缓存中是否存在
	InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
	if (InjectionMetadata.needsRefresh(metadata, clazz)) {
		synchronized (this.injectionMetadataCache) {
           	 // 再次查询是否存在,防止加锁过程中加入
			metadata = this.injectionMetadataCache.get(cacheKey);
			if (InjectionMetadata.needsRefresh(metadata, clazz)) {
				if (metadata != null) {
					metadata.clear(pvs);
				}
				metadata = buildAutowiringMetadata(clazz);
				this.injectionMetadataCache.put(cacheKey, metadata);
			}
		}
	}
	return metadata;
}
	
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
	Set<InjectedElement> checkedElements = new LinkedHashSet<>									(this.injectedElements.size());
	for (InjectedElement element : this.injectedElements) {
		Member member = element.getMember();
		if (!beanDefinition.isExternallyManagedConfigMember(member)) {
			beanDefinition.registerExternallyManagedConfigMember(member);
			checkedElements.add(element);
			if (logger.isTraceEnabled()) {
				.... //日志
			}
		}
	}
	this.checkedElements = checkedElements;
}

​ 后置处理器五、SmartInstantiationAwareBeanPostProcessor获取早期暴露的引用

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
   Object exposedObject = bean;
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
            SmartInstantiationAwareBeanPostProcessor ibp = 												(SmartInstantiationAwareBeanPostProcessor) bp;
            exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
         }
      }
   }
   return exposedObject;
}

​ getEarlyBeanReference获取早期暴露的引用,

public Object getEarlyBeanReference(Object bean, String beanName) {
   Object cacheKey = getCacheKey(bean.getClass(), beanName);
   this.earlyProxyReferences.put(cacheKey, bean);
   return wrapIfNecessary(bean, beanName, cacheKey);
}

​ wrapIfNecessary生成代理类

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
   if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
      return bean;
   }
   if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
      return bean;
   }
   if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
      this.advisedBeans.put(cacheKey, Boolean.FALSE);
      return bean;
   }

   // 根据类名获取需要代理类的Advice
   Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(),
            beanName, null);
   if (specificInterceptors != DO_NOT_PROXY) {
      this.advisedBeans.put(cacheKey, Boolean.TRUE);
      // 创建代理类
      Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new 				SingletonTargetSource(bean));
      this.proxyTypes.put(cacheKey, proxy.getClass());
      return proxy;
   }

   this.advisedBeans.put(cacheKey, Boolean.FALSE);
   return bean;
}

​ populateBean属性注入入口。

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   if (bw == null) {
      if (mbd.hasPropertyValues()) {
         .... //异常
      }
      else {
         return;
      }
   }

   // 判断是否有后置处理器,调用后置处理器---后置处理器二
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) 				bp;
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               return;
            }
         }
      }
   }
   // 
   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   // 判断注入方式
   if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == 						AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // 根据名称获取需要注入的属性,判断pvs中不存在但是实体类的却存在的属性,加入到依赖的类集合中
      // 注入方式可以通过@Bean注解的autowire属性进行控制,但已经不推荐是使用,默认AUTOWIRE_NO
      if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }
      // 类似autowireByName
      if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }
      pvs = newPvs;
   }

   // 判断是否存在后置处理器
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   boolean needsDepCheck = 																	(mbd.getDependencyCheck()!=AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

   PropertyDescriptor[] filteredPds = null;
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      // 遍历后置处理器
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = 
              (InstantiationAwareBeanPostProcessor)bp;
            // 对需要注入的类进行注入---后置处理器六
            PropertyValues pvsToUse = ibp.postProcessProperties(pvs, 								 bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               if (filteredPds == null) {
                  // 去除ignoredDependencyTypes添加的依赖,准备环境时注入
                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, 							mbd.allowCaching);
               }
               // 对需要注入的PropertyValues进行处理---后置处理器七
               pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, 								bw.getWrappedInstance(), beanName);
               if (pvsToUse == null) {
                  return;
               }
            }
            // 需要注入的PropertyValues
            pvs = pvsToUse;
         }
      }
   }
   if (needsDepCheck) {
      if (filteredPds == null) {
         // 去除ignoredDependencyTypes添加的依赖,准备环境时注入
         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      }
      // check检查
      checkDependencies(beanName, mbd, filteredPds, pvs);
   }

   if (pvs != null) {
      // PropertyValues属性注入
      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) {
      // propertyNames属性是否存在于集合中
      if (containsBean(propertyName)) {
         // 获取实例
         Object bean = getBean(propertyName);
         pvs.add(propertyName, bean);
         // 向依赖的集合中加入以来的Bean
         registerDependentBean(propertyName, beanName);
         if (logger.isTraceEnabled()) {
            .... // 日志
         }
      }
      else {
         if (logger.isTraceEnabled()) {
            .... // 日志
         }
      }
   }
}

​ dependentBeanMap和dependenciesForBeanMap加入该类。

public void registerDependentBean(String beanName, String dependentBeanName) {
   String canonicalName = canonicalName(beanName);
   // dependentBeanMap中加入实体类
   synchronized (this.dependentBeanMap) {
      Set<String> dependentBeans =
          this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>			 (8));
      if (!dependentBeans.add(dependentBeanName)) {
         return;
      }
   }
   // dependenciesForBeanMap、dependenciesForBean中加入实体类
   synchronized (this.dependenciesForBeanMap) {
      Set<String> dependenciesForBean =
         this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new 				LinkedHashSet<>(8));
      dependenciesForBean.add(canonicalName);
   }
}

​ autowireByType通过类型进行注入,类似inject方法通过Autowired注解注入过程。

protected void autowireByType(String beanName, 
	AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

   // 类型转换类
   TypeConverter converter = getCustomTypeConverter();
   if (converter == null) {
      converter = bw;
   }

   Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
   String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
   for (String propertyName : propertyNames) {
      try {
         PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
         
         if (Object.class != pd.getPropertyType()) {
            MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
            // PriorityOrdered优先级判断是否可立即注入
            boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
            DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, 				eager);
            // 处理依赖,类似inject方法以Autowired注解注入的过程
            Object autowiredArgument = resolveDependency(desc, beanName, 								autowiredBeanNames, converter);
            if (autowiredArgument != null) {
               pvs.add(propertyName, autowiredArgument);
            }
            for (String autowiredBeanName : autowiredBeanNames) {
               // 注册以来的Bean
               registerDependentBean(autowiredBeanName, beanName);
               if (logger.isTraceEnabled()) {
                  .... // 日志
               }
            }
            autowiredBeanNames.clear();
         }
      }
      catch (BeansException ex) {
         .... // 异常
      }
   }
}

​ 后置处理器六、postProcessProperties后置处理器,注入依赖入口。

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String 		beanName) {	
   // 获取需要注入的属性@Resource注解方式
   InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
   try {
      // 通过反射进依赖注入
      metadata.inject(bean, beanName, pvs);
   }
   catch (Throwable ex) {
      .... //异常
   }
   return pvs;
}

​ inject注入依赖,checkedElements和injectedElements有applyMergedBeanDefinitionPostProcessors后置处理器加入。

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) 		throws Throwable {
   Collection<InjectedElement> checkedElements = this.checkedElements;
   Collection<InjectedElement> elementsToIterate =
         (checkedElements != null ? checkedElements : this.injectedElements);
   if (!elementsToIterate.isEmpty()) {
      for (InjectedElement element : elementsToIterate) {
         if (logger.isTraceEnabled()) {
            .... // 日志
         }
         // 注入依赖
         element.inject(target, beanName, pvs);
      }
   }
}	

​ findResourceMetadata获取需要注入的属性

private InjectionMetadata findResourceMetadata(String beanName, final Class<?> clazz, 		@Nullable PropertyValues pvs) {

   //  获取缓存的键
   String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
   // 获取缓存中的Metqadate
   InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
   if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  		synchronized (this.injectionMetadataCache) {
 			metadata = this.injectionMetadataCache.get(cacheKey);
 			if (InjectionMetadata.needsRefresh(metadata, clazz)) {
    			if (metadata != null) {
       				metadata.clear(pvs);
    			}
        	// 新建属性值
    		metadata = buildResourceMetadata(clazz);
    		this.injectionMetadataCache.put(cacheKey, metadata);
 			}
 		}
 	}
   return metadata;
}

​ inject反射注入属性分为方法注入和属性注入,getResourceToInject获取需要的值。

protected void inject(Object target, @Nullable String requestingBeanName, @Nullable 		PropertyValues pvs) throws Throwable {

   if (this.isField) {
      // 属性注入
      Field field = (Field) this.member;
      ReflectionUtils.makeAccessible(field);
      field.set(target, getResourceToInject(target, requestingBeanName));
   }
   else {
      if (checkPropertySkipping(pvs)) {
         return;
      }
      try {
         // 方法注入
         Method method = (Method) this.member;
         ReflectionUtils.makeAccessible(method);
         method.invoke(target, getResourceToInject(target, requestingBeanName));
      }
      catch (InvocationTargetException ex) {
         .... //异常
      }
   }
}

​ postProcessProperties后置处理器,处理以@Autowired和@Value注解加入的属性进行注入

@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
   InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
   try {
      metadata.inject(bean, beanName, pvs);
   }
   catch (BeanCreationException ex) {
      .... //异常
   }
   catch (Throwable ex) {
      .... //异常
   }
   return pvs;
}

​ findAutowiringMetadata获取以@Autowired注解和@Value注解修饰的变量。

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
  
   // 缓存的key
   String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
   InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
   if (InjectionMetadata.needsRefresh(metadata, clazz)) {
      synchronized (this.injectionMetadataCache) {
         metadata = this.injectionMetadataCache.get(cacheKey);
         if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            if (metadata != null) {
               metadata.clear(pvs);
            }
            // 对注解进行扫描遍历,找到该类的所有@Autowired和@Value注解
            metadata = buildAutowiringMetadata(clazz);
            this.injectionMetadataCache.put(cacheKey, metadata);
         }
      }
   }
   return metadata;
}

​ inject反射进行属性的注入

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) 	throws Throwable {
      Field field = (Field) this.member;
      Object value;
      if (this.cached) {
         value = resolvedCachedArgument(beanName, this.cachedFieldValue);
      }
      else {
         DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
         desc.setContainingClass(bean.getClass());
         Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
         Assert.state(beanFactory != null, "No BeanFactory available");
         // 类型转换类
         TypeConverter typeConverter = beanFactory.getTypeConverter();
         try {
            // 具体需要的类处理
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, 					typeConverter);
         }
         catch (BeansException ex) {
            .... //异常
         }
         synchronized (this) {
            if (!this.cached) {
               if (value != null || this.required) {
                  this.cachedFieldValue = desc;
                  registerDependentBeans(beanName, autowiredBeanNames);
                  if (autowiredBeanNames.size() == 1) {
                     String autowiredBeanName = autowiredBeanNames.iterator().next();
                     if (beanFactory.containsBean(autowiredBeanName) &&
                           beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                        this.cachedFieldValue = new ShortcutDependencyDescriptor(
                              desc, autowiredBeanName, field.getType());
                     }
                  }
               }
               else {
                  this.cachedFieldValue = null;
               }
               this.cached = true;
            }
         }
      }
      if (value != null) {
         ReflectionUtils.makeAccessible(field);
         field.set(bean, value);
      }
   }
}

​ resolveDependency具体类的获取。

public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String 			requestingBeanName,@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter 	typeConverter) throws BeansException {
   descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
   if (Optional.class == descriptor.getDependencyType()) {
      return createOptionalDependency(descriptor, requestingBeanName);
   }
   else if (ObjectFactory.class == descriptor.getDependencyType() ||
         ObjectProvider.class == descriptor.getDependencyType()) {
      return new DependencyObjectProvider(descriptor, requestingBeanName);
   }
   else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
      return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
   }
   else {
      Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
            descriptor, requestingBeanName);
      if (result == null) {
         // 获取需要的类
         result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, 			typeConverter);
      }
      return result;
   }
}

​ doResolveDependency注入类选择最终逻辑,通过Order、Primary以及名称筛选需要的类实例。

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String 		beanName,@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter 				typeConverter) throws BeansException {
   	InjectionPoint previousInjectionPoint = 															ConstructorResolver.setCurrentInjectionPoint(descriptor);
   try {
      Object shortcut = descriptor.resolveShortcut(this);
      if (shortcut != null) {
         return shortcut;
      }

      // 获取需要注入类的类型
      Class<?> type = descriptor.getDependencyType();
      Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
      if (value != null) {
         if (value instanceof String) {
           	// 具体的类型处理,会处理@Value注解中${}引入的值,从propertySouces中查找进行替换
            // 主要针对expr类型进行解析
            String strVal = resolveEmbeddedValue((String) value);
            BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                  getMergedBeanDefinition(beanName) : null);
            value = evaluateBeanDefinitionString(strVal, bd);
         }
         // 类型转换类
         TypeConverter converter = (typeConverter != null ? typeConverter : 							getTypeConverter());
         try {
            // 类型转换
            return converter.convertIfNecessary(value, type, 											descriptor.getTypeDescriptor());
         }
         catch (UnsupportedOperationException ex) {
            return (descriptor.getField() != null ?
                  converter.convertIfNecessary(value, type, descriptor.getField()) :
                  converter.convertIfNecessary(value, type, 											descriptor.getMethodParameter()));
         }
      }
	 // 处理实例集合注入,处理类似以list、map等形式的注入
      Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, 			typeConverter);
      if (multipleBeans != null) {
         return multipleBeans;
      }

      // 匹配到的所有类
      Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, 					descriptor);
      // 未匹配到处理
      if (matchingBeans.isEmpty()) {
         if (isRequired(descriptor)) {
            raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
         }
         return null;
      }

      String autowiredBeanName;
      Object instanceCandidate;
 	  // 匹配多个处理
      if (matchingBeans.size() > 1) {
         // 根据优先级标签进行筛选
         autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
         if (autowiredBeanName == null) {
            if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
               return descriptor.resolveNotUnique(descriptor.getResolvableType(), 							matchingBeans);
            }
            else {
               return null;
            }
         }
         // 根据获取的名称获取
         instanceCandidate = matchingBeans.get(autowiredBeanName);
      }
      else {
         // 匹配的标签只有一个的情况
         Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
         autowiredBeanName = entry.getKey();
         instanceCandidate = entry.getValue();
      }

      if (autowiredBeanNames != null) {
         autowiredBeanNames.add(autowiredBeanName);
      }
      if (instanceCandidate instanceof Class) {
         instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
      }
      Object result = instanceCandidate;
      if (result instanceof NullBean) {
         if (isRequired(descriptor)) {
            raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
         }
         result = null;
      }
      if (!ClassUtils.isAssignableValue(type, result)) {
         .... //异常
      }
      return result;
   }
   finally {
      ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
   }
}

​ determineAutowireCandidate对加有优先级标签的注解的过滤。

protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
   Class<?> requiredType = descriptor.getDependencyType();
   // 针对加@Primary注解的类的处理,@Primary注解实在注册BeanDefinition时加入
   String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
   if (primaryCandidate != null) {
      return primaryCandidate;
   }
   // 针对加@Order标签的类的处理
   String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
   if (priorityCandidate != null) {
      return priorityCandidate;
   }
   // 循环进行匹配,根据名称进行匹配
   for (Map.Entry<String, Object> entry : candidates.entrySet()) {
      String candidateName = entry.getKey();
      Object beanInstance = entry.getValue();
      if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) 		|| matchesBeanName(candidateName, descriptor.getDependencyName())) {
         return candidateName;
      }
   }
   return null;
}

​ 后置处理器七、postProcessPropertyValues对PropertyValues进行处理

public PropertyValues postProcessPropertyValues(
      PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
   if (!this.validatedBeanNames.contains(beanName)) {
      if (!shouldSkip(this.beanFactory, beanName)) {
         List<String> invalidProperties = new ArrayList<>();
         for (PropertyDescriptor pd : pds) {
            // 判断是否存在@Required注解,已不推荐使用,存在但注入属性不包含则报错
            if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) {
               invalidProperties.add(pd.getName());
            }
         }
         if (!invalidProperties.isEmpty()) {
            .... //异常
         }
      }
      this.validatedBeanNames.add(beanName);
   }
   return pvs;
}

​ applyPropertyValues注入PropertyValues。

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, 	PropertyValues pvs) {
   if (pvs.isEmpty()) {
      return;
   }

   if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
      ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
   }

   MutablePropertyValues mpvs = null;
   List<PropertyValue> original;

   if (pvs instanceof MutablePropertyValues) {
      mpvs = (MutablePropertyValues) pvs;
      if (mpvs.isConverted()) {
         try {
            bw.setPropertyValues(mpvs);
            return;
         }
         catch (BeansException ex) {
            .... //异常
         }
      }
      original = mpvs.getPropertyValueList();
   }
   else {
      original = Arrays.asList(pvs.getPropertyValues());
   }

   // 自定义类型转换类
   TypeConverter converter = getCustomTypeConverter();
   if (converter == null) {
      converter = bw;
   }
   // Bean定义处理类
   BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, 			beanName, mbd, converter);

   // 拷贝值集合
   List<PropertyValue> deepCopy = new ArrayList<>(original.size());
   boolean resolveNecessary = false;
   for (PropertyValue pv : original) {
      if (pv.isConverted()) {
         deepCopy.add(pv);
      }
      else {
         String propertyName = pv.getName();
         Object originalValue = pv.getValue();
         if (originalValue == AutowiredPropertyMarker.INSTANCE) {
            Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
            if (writeMethod == null) {
               .... //异常
            }
            originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), 				true);
         }
         // 进行类型转换
         Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
         Object convertedValue = resolvedValue;
         boolean convertible = bw.isWritableProperty(propertyName) &&
               !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
         if (convertible) {
           	// 属性转换
            convertedValue = convertForProperty(resolvedValue, propertyName, bw, 					   converter);
         }
         // 
         if (resolvedValue == originalValue) {
            if (convertible) {
               // 设置值
               pv.setConvertedValue(convertedValue);
            }
            // 加入到拷贝集合
            deepCopy.add(pv);
         }
         else if (convertible && originalValue instanceof TypedStringValue &&
            !((TypedStringValue) originalValue).isDynamic() &&
            !(convertedValue instanceof Collection || 										    ObjectUtils.isArray(convertedValue))) {
            pv.setConvertedValue(convertedValue);
            deepCopy.add(pv);
         }
         else {
            resolveNecessary = true;
            deepCopy.add(new PropertyValue(pv, convertedValue));
         }
      }
   }
   if (mpvs != null && !resolveNecessary) {
      mpvs.setConverted();
   }

   // 
   try {
      // 实体类设置值
      bw.setPropertyValues(new MutablePropertyValues(deepCopy));
   }
   catch (BeansException ex) {
      .... //异常
   }
}

​ initializeBean初始化处理,主要针对Aware类、用户自定义以及实现了InitializingBean.afterPropertiesSet方法处理。

protected Object initializeBean(String beanName, Object bean, 
    @Nullable RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   }
   else {
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      // 初始化后置处理器---后置处理器八
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      // 初始化方法处理
      invokeInitMethods(beanName, wrappedBean, mbd);
   }
   catch (Throwable ex) {
      .... //异常
   }
   if (mbd == null || !mbd.isSynthetic()) {
      // 初始化后置处理器---后置处理器二
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }

   return wrappedBean;
}
后置处理器八、postProcessBeforeInitialization初始化前处理
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, 
   String beanName) throws BeansException {
   Object result = existingBean;
   	for (BeanPostProcessor processor : getBeanPostProcessors()) {
  		Object current = processor.postProcessBeforeInitialization(result, beanName);
  		if (current == null) {
     		return result;
  		}
  		result = current;
  	}
  	return result;
}

postProcessBeforeInitialization初始化前处理
public Object postProcessBeforeInitialization(Object bean, String beanName) throws 			BeansException {
  	// 判断类是否集成自这些Aware
	if (!(bean instanceof EnvironmentAware || bean instanceof 									EmbeddedValueResolverAware || bean instanceof ResourceLoaderAware || bean 				instanceof ApplicationEventPublisherAware || bean instanceof MessageSourceAware 
         || bean instanceof ApplicationContextAware)){
			return bean;
		}
		AccessControlContext acc = null;
		if (System.getSecurityManager() != null) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}
		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
             // 反射执行Aware
			invokeAwareInterfaces(bean);
		}

		return bean;
	}
// 分种类型的Aware执行
private void invokeAwareInterfaces(Object bean) {
	if (bean instanceof EnvironmentAware) {
         ((EnvironmentAware)bean).setEnvironment(
            this.applicationContext.getEnvironment());
	}
	if (bean instanceof EmbeddedValueResolverAware) {
		((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
             	this.embeddedValueResolver);
	}
	if (bean instanceof ResourceLoaderAware) {
		((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
	}
	if (bean instanceof ApplicationEventPublisherAware) {
		((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(
             	this.applicationContext);
	}
	if (bean instanceof MessageSourceAware) {
		((MessageSourceAware) bean).setMessageSource(this.applicationContext);
	}
	if (bean instanceof ApplicationContextAware) {
		((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
	}
}

​ invokeInitMethods反射执行初始化方法,先afterPropertiesSet再用户自定义的init-method。

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition 	mbd) throws Throwable {

   boolean isInitializingBean = (bean instanceof InitializingBean);
   if (isInitializingBean && (mbd == null || 												!mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      if (logger.isTraceEnabled()) {
         .... // 日志
      }
      if (System.getSecurityManager() != null) {
         try {
            AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
               ((InitializingBean) bean).afterPropertiesSet();
               return null;
            }, getAccessControlContext());
         }
         catch (PrivilegedActionException pae) {
            .... //异常
         }
      }
      else {
         // afterPropertiesSet方法使用
         ((InitializingBean) bean).afterPropertiesSet();
      }
   }
   // 用户自定义的初始化方法执行init-method属性
   if (mbd != null && bean.getClass() != NullBean.class) {
      String initMethodName = mbd.getInitMethodName();
      if (StringUtils.hasLength(initMethodName) &&
            !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodNa·e)) {
         invokeCustomInitMethod(beanName, bean, mbd);
      }
   }
}

三、总结

​ Bean的注入开始于AbstractApplicationContext.preInstantiateSingletons(自己创建的Bean实例),主要以后置处理进行处理,首先根据后置处理器AbstractAutoProxyCreator.postProcessBeforeInstantiation判断是否是用户自定义的targetClass并创建代理Bean,以AbstractAdvisingBeanPostProcessor.postProcessAfterInitialization结束(时序图以后置处理器类AbstractAdvisingBeanPostProcessor是为了初始化后使用),接着获取实例,这里有多种策略可以是Supplier创建实例,FactoryMethod创建实例,构造方法创建实例(注入时创建实例的主要方式),其中会有AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors后置处理器方法来解决Lookup标签以及构造方法注入问题。MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition,向已创建实例集合加入该实例名称和获取实例中@Autowired、@Value、@Resource注解的属性并放入待注入集合中,然后AbstractAutoProxyCreator.getEarlyBeanReference判断是否需要创建代理类,用于早期暴露用于三级缓存解决循环依赖问题,InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation置灰返回是否,若返回否直接返回不进行初始化和注入操作,InstantiationAwareBeanPostProcessor.postProcessProperties进行依赖注入,分为Autowired和Value注解以及@Resource注解两种情况进行注入,每种方式走不同的后置处理器,InstantiationAwareBeanPostProcessor.postProcessPropertyValues判断是否有@Required注解(忽略),invokeAwareMethods进行Aware类的执行,AbstractAutowireCapableBeanFactory.postProcessBeforeInitialization也会调用Aware类,InitializingBean.afterPropertiesSet以及自定义类的调用,最后进行初始化后处理BeanPostProcessor.postProcessAfterInitialization,会根据需要判断是否需要进行代理处理。后置处理器有多个进行扫描后时会进行排序插入,这里只列举个别后置处理器,后置处理器的循环调用是框架高扩展性的重要体现,此外还有Aware类自定义类型转换类来解决扩展性问题。@Lookup注解修饰的方法用于多实例模式的注入,会创建代理类替换方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值