基于Spring注解的上下文初始化过程源码解析(三…

2019-08-16 12:26:20来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

基于Spring注解的上下文初始化过程源码解析(三)

上一篇跟完了 refresh 方法中第一个重要的方法 invokeBeanFactoryPostProcessors,

这篇继续分析 refresh 方法中第二个比较重要的 finishBeanFactoryInitialization 方法 

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	/**
	 * 初始化此上下文的转换服务
	 */
	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));
	}

	/**
	 * 如果之前没有注册 bean 后置处理器(例如 PropertyPlaceholderConfigurer)
	 * 则注册默认的嵌入值解析器:此时主要用于注释属性值的解析
	 */
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}
	// 获取 LoadTimeWeaverAware 的 BeanName 集合
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		// 初始化 LoadTimeWeaverAware 以允许尽早注册其变换器
		getBean(weaverAwareName);
	}

	// 停止使用临时 ClassLoader 进行类型匹配
	beanFactory.setTempClassLoader(null);

	// 允许缓存所有 BeanDefinition 元数据,不期望进一步更改
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	// 实例化所有不是懒加载的单例对象
	beanFactory.preInstantiateSingletons();
} 

实例化所有非懒加载的单例对象方法中包含了 getBean 方法,先看  preInstantiateSingletons 方法

public void preInstantiateSingletons() throws BeansException {
	// 所有已注册的 BeanName 集合
	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
	// 触发所有非延迟加载单例 Bean 的初始化,主要步骤为调用 getBean()方法
	for (String beanName : beanNames) {
		// 合并父 BeanDefinition
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		// 不是抽象类、是单例且不是懒加载的 Bean
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			// 判断该 Bean 是否是一个 FactoryBean
			if (isFactoryBean(beanName)) {
				/**
				 * 如果是 FactoryBean 则需要加上&才能实例化该 Bean
				 * 否则实例化的是该 FactoryBean 生产的对象
				 */
				Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
				// 再次确认是 FactoryBean 的子类
				if (bean instanceof FactoryBean) {
					// 强转为父类
					final FactoryBean<?> factory = (FactoryBean<?>) bean;
					boolean isEagerInit;
					/**
					 * SecurityManager 不为空并且是 SmartFactoryBean 的子类
					 *
					 * SmartFactoryBean 的子类有 EagerInitFactory 和 NonPrivilegedFactoryBean
					 */
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						//
						isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
											((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
					} else {
						// 是 SmartFactoryBean 的子类并且是迫切需要被实例化的
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					// 如果是迫切需要被实例化的类,则实例化
					if (isEagerInit) {
						getBean(beanName);
					}
				}
			} else {
				// 实例化
				getBean(beanName);
			}
		}
	}
	// 触发所有适用 bean 的后初始化回调
	for (String beanName : beanNames) {
		Object singletonInstance = getSingleton(beanName);
		/**
		 * 是 SmartInitializingSingleton 的子类
		 *
		 * EventListenerMethodProcessor 是 SmartInitializingSingleton 的子类
		 */
		if (singletonInstance instanceof SmartInitializingSingleton) {
			// 强转为 SmartInitializingSingleton
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					smartSingleton.afterSingletonsInstantiated();
					return null;
				}, getAccessControlContext());
			} else {
				// 回调 afterSingletonsInstantiated 方法
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}
getBean 方法是一个空壳方法,内部调用了 doGetBean 方法
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
		@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

	/**
	 * 通过 name 获取 BeanName。这里不使用 name 直接作为 BeanName 有两个原因:
	 *
	 *  1.name 可能会以 & 字符开头,表明调用者想获取 FactoryBean 对象本身的实例,
	 * 	  而非 FactoryBean 实现类所创建的 Bean 对象实例。
	 *    在 BeanFactory 中,FactoryBean 的实现类和其他的 Bean 存储方式是一致的,
	 *    即<BeanName, BeanInstance>,BeanName中是没有 & 这个字符的,
	 *    所以需要将 name 的首字符 & 移除,这样才能从缓存里取到 FactoryBean 创建的实例
	 *  2.该 Bean 对象可能存在别名的问题
	 */
	// 解析 BeanName 为规范名称
	final String beanName = transformedBeanName(name);
	Object bean;

	/**
	 * 解决循环依赖问题【通过两次重载的 getSingleton() 方法和一次后置处理器方法的调用来解决循环依赖】
	 */

	// 第一次调用 getSingleton() 方法,检查单个缓存以手动注册单例。
	// 获取在给定名称下注册的(原始)单例对象。
	Object sharedInstance = getSingleton(beanName);
	if (sharedInstance != null && args == null) {
		if (logger.isTraceEnabled()) {
			if (isSingletonCurrentlyInCreation(beanName)) {
				logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
						"' that is not fully initialized yet - a consequence of a circular reference");
			}
			else {
				logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
			}
		}
		// 获取给定 bean 实例的对象,如果是 FactoryBean,则为 bean 实例本身或其创建的对象。
		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
	}
	// 已经创建过该实例对象
	else {
		// 如果已经创建了这个 bean 实例,则会失败:我们可以在循环引用中完成。
		// prototype 对象在每次 get 的时候创建,单例则不需要创建
		if (isPrototypeCurrentlyInCreation(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}

		// 检查此工厂中是否存在 BeanDefinition
		BeanFactory parentBeanFactory = getParentBeanFactory();
		// 父工厂存在且不包含解析后的 beanName
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			String nameToLookup = originalBeanName(name);
			if (parentBeanFactory instanceof AbstractBeanFactory) {
				// 转换调用 doGetBean 方法
				return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
						nameToLookup, requiredType, args, typeCheckOnly);
			}
			else if (args != null) {
				// 使用显式 args 委托父级
				return (T) parentBeanFactory.getBean(nameToLookup, args);
			}
			else if (requiredType != null) {
				// 没有参数,委托标准的 getBean 方法
				return parentBeanFactory.getBean(nameToLookup, requiredType);
			}
			else {
				return (T) parentBeanFactory.getBean(nameToLookup);
			}
		}

		if (!typeCheckOnly) {
			markBeanAsCreated(beanName);
		}

		try {
			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
			// 校验是否是抽象的
			checkMergedBeanDefinition(mbd, beanName, args);

			// 初始化当前 Bean 依赖的 Bean【被 @DependsOn 注解指明需要依赖的 Bean】
			// Guarantee initialization of beans that the current bean depends on.
			String[] dependsOn = mbd.getDependsOn();
			if (dependsOn != null) {
				for (String dep : dependsOn) {
					// 校验是否是依赖项
					if (isDependent(beanName, dep)) {
						// 抛出循环依赖异常
						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
								"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
					}
					// 为给定 bean 注册依赖 bean
					registerDependentBean(dep, beanName);
					try {
						// 获取给定的 bean 实例
						getBean(dep);
					}
					catch (NoSuchBeanDefinitionException ex) {
						// 抛出依赖项缺失异常
						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
					}
				}
			}

			// 创建 Bean 实例
			if (mbd.isSingleton()) {
				// 第二次调用,解决循环依赖问题
				sharedInstance = getSingleton(beanName, () -> {
					try {
						return createBean(beanName, mbd, args);
					}
					catch (BeansException ex) {
						destroySingleton(beanName);
						throw ex;
					}
				});
				bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
			}

			else if (mbd.isPrototype()) {
				// 原型则创建新的实例
				Object prototypeInstance;
				try {
					beforePrototypeCreation(beanName);
					prototypeInstance = createBean(beanName, mbd, args);
				}
				finally {
					afterPrototypeCreation(beanName);
				}
				bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
			}

			else {
				String scopeName = mbd.getScope();
				final Scope scope = this.scopes.get(scopeName);
				if (scope == null) {
					throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
				}
				try {
					Object scopedInstance = scope.get(beanName, () -> {
						beforePrototypeCreation(beanName);
						try {
							return createBean(beanName, mbd, args);
						}
						finally {
								afterPrototypeCreation(beanName);
						}
					});
					bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
				}
				catch (IllegalStateException ex) {
					throw new BeanCreationException(beanName,
							"Scope '" + scopeName + "' is not active for the current thread; consider " +
							"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
							ex);
				}
			}
		}
		catch (BeansException ex) {
			cleanupAfterBeanCreationFailure(beanName);
			throw ex;
		}
	}

	// Check if required type matches the type of the actual bean instance.
	if (requiredType != null && !requiredType.isInstance(bean)) {
		try {
			T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
			if (convertedBean == null) {
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
			return convertedBean;
		}
		catch (TypeMismatchException ex) {
			if (logger.isTraceEnabled()) {
				logger.trace("Failed to convert bean '" + name + "' to required type '" +
							ClassUtils.getQualifiedName(requiredType) + "'", ex);
			}
			throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
		}
	}
	return (T) bean;
}  

 FactoryBean 是一种特殊的 Bean,它能产生新的 Bean,获取的时候需要加'&'字符,否则获取的是其产生的 Bean。

Spring 通过调用两次重载的 getSingleton 方法和一次后置处理器的调用来解决 Bean 之间的循环依赖问题,其中第二次调用 getSingleton 方法传了一个lambda表达式,createBean 方法断点进去

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

	if (logger.isTraceEnabled()) {
		logger.trace("Creating instance of bean '" + beanName + "'");
	}
	RootBeanDefinition mbdToUse = mbd;

	// Make sure bean class is actually resolved at this point, and
	// clone the bean definition in case of a dynamically resolved Class
	// which cannot be stored in the shared merged bean definition.
	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		mbdToUse = new RootBeanDefinition(mbd);
		mbdToUse.setBeanClass(resolvedClass);
	}

	// Prepare method overrides.
	try {
		mbdToUse.prepareMethodOverrides();
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
				beanName, "Validation of method overrides failed", ex);
	}

	try {
		// 第一次调用后置处理器
		/*
		 * InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
		 * Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
		 */
		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
		Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
		if (bean != null) {
			return bean;
		}
	}
	catch (Throwable ex) {
		throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
				"BeanPostProcessor before instantiation of bean failed", ex);
	}

	try {
		//
		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		if (logger.isTraceEnabled()) {
			logger.trace("Finished creating instance of bean '" + beanName + "'");
		}
		return beanInstance;
	}catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
		// A previously detected exception with proper bean creation context already,
		// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
		throw ex;
	}
	catch (Throwable ex) {
		throw new BeanCreationException(
				mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
	}
}  

我们知道,一个对象只有具有完整的 Spring 生命周期才能称为一个 Bean,这里开始 Spring 的后置处理器调用过程,一共需要经过五大后置处理器的九个方法:

  1 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  2         throws BeanCreationException {
  3 
  4     /**
  5      * 初始化是实例化的一部分
  6      *
  7      * 初始化:Initialization
  8      * 实例化:Instantiation
  9      *
 10      * BeanPostProcessor 的直接实现类能够干预 Bean 的初始化过程
 11      * BeanPostProcessor 的继承类能够干预 Bean 的实例化过程
 12      */
 13 
 14     // Instantiate the bean.
 15     BeanWrapper instanceWrapper = null;
 16     if (mbd.isSingleton()) {
 17         instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
 18     }
 19     if (instanceWrapper == null) {
 20         // 第二次调用后置处理器【推断构造方法来实例化 Bean】
 21         /*
 22          * SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
 23          * Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
 24          */
 25         instanceWrapper = createBeanInstance(beanName, mbd, args);
 26     }
 27     // 此时还未完成依赖 Bean 的注入
 28     final Object bean = instanceWrapper.getWrappedInstance();
 29     Class<?> beanType = instanceWrapper.getWrappedClass();
 30     if (beanType != NullBean.class) {
 31         mbd.resolvedTargetType = beanType;
 32     }
 33 
 34     // Allow post-processors to modify the merged bean definition.
 35     synchronized (mbd.postProcessingLock) {
 36         if (!mbd.postProcessed) {
 37             try {
 38                 // 第三次调用后置处理器【缓存 Spring 的配置信息】
 39                 /*
 40                  * MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
 41                  * bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
 42                  */
 43                 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
 44             }
 45             catch (Throwable ex) {
 46                 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 47                         "Post-processing of merged bean definition failed", ex);
 48             }
 49             mbd.postProcessed = true;
 50         }
 51     }
 52 
 53     // Eagerly cache singletons to be able to resolve circular references
 54     // even when triggered by lifecycle interfaces like BeanFactoryAware.
 55     boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
 56             isSingletonCurrentlyInCreation(beanName));
 57     if (earlySingletonExposure) {
 58         if (logger.isTraceEnabled()) {
 59             logger.trace("Eagerly caching bean '" + beanName +
 60                     "' to allow for resolving potential circular references");
 61         }
 62         // 第四次调用后置处理器【Spring 借助了这一次后置处理器的调用外加两次重载的 getSingleton() 方法来解决循环依赖】
 63         /*
 64          * SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
 65          * exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
 66          */
 67         addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
 68     }
 69 
 70     // 初始化 Bean 实例
 71     // Initialize the bean instance.
 72     Object exposedObject = bean;
 73     try {
 74         /**
 75          * 通过调用两个后置处理器的方法,完成 Bean 属性的填充【非常重要】
 76          */
 77 
 78         // 第五次调用后置处理器【返回 true 才会进行属性填充,可以干预某个 Bean 的装配填充】
 79         /*
 80          * InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
 81          * ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName);
 82          */
 83         // 第六次调用后置处理器
 84         /*
 85          * InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
 86          * PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
 87          * pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
 88          */
 89         populateBean(beanName, mbd, instanceWrapper);
 90 
 91         /**
 92          * 通过调用两次后置处理器,完成 Bean 的初始化
 93          */
 94 
 95         // 第七次调用后置处理器【BeanPostProcessor 的直接实现类调用】
 96         /*
 97          * Object current = processor.postProcessBeforeInitialization(result, beanName);
 98          */
 99         // 第八次调用后置处理器【BeanPostProcessor 的直接实现类调用】
100         /*
101          * Object current = processor.postProcessAfterInitialization(result, beanName);
102          */
103         exposedObject = initializeBean(beanName, exposedObject, mbd);
104     }
105     catch (Throwable ex) {
106         if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
107             throw (BeanCreationException) ex;
108         }
109         else {
110             throw new BeanCreationException(
111                     mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
112         }
113     }
114 
115     if (earlySingletonExposure) {
116         Object earlySingletonReference = getSingleton(beanName, false);
117         if (earlySingletonReference != null) {
118             if (exposedObject == bean) {
119                 exposedObject = earlySingletonReference;
120             }
121             else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
122                 String[] dependentBeans = getDependentBeans(beanName);
123                 Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
124                 for (String dependentBean : dependentBeans) {
125                     if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
126                         actualDependentBeans.add(dependentBean);
127                     }
128                 }
129                 if (!actualDependentBeans.isEmpty()) {
130                     throw new BeanCurrentlyInCreationException(beanName,
131                             "Bean with name '" + beanName + "' has been injected into other beans [" +
132                             StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
133                             "] in its raw version as part of a circular reference, but has eventually been " +
134                             "wrapped. This means that said other beans do not use the final version of the " +
135                             "bean. This is often the result of over-eager type matching - consider using " +
136                             "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
137                 }
138             }
139         }
140     }
141 
142     // Register bean as disposable.
143     try {
144         // 第九次调用后置处理器【销毁】
145         /*
146          * DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
147          * dabpp.requiresDestruction(bean);
148          */
149         registerDisposableBeanIfNecessary(beanName, bean, mbd);
150     }
151     catch (BeanDefinitionValidationException ex) {
152         throw new BeanCreationException(
153                 mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
154     }
155 
156     return exposedObject;
157 
158     /**
159      * 其中 AOP 是借助了第一次和第八次调用后置处理器来产生代理 Bean
160      */
161 }

下面就分别进入这五大后置处理器的九个方法代码一探究竟:

第一次调用了 InstantiationAwareBeanPostProcessor 的 postProcessBeforeInstantiation 方法

 1 protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
 2     Object bean = null;
 3     if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
 4         // Make sure bean class is actually resolved at this point.
 5         if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
 6             Class<?> targetType = determineTargetType(beanName, mbd);
 7             if (targetType != null) {
 8                 bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
 9                 if (bean != null) {
10                     bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
11                 }
12             }
13         }
14         mbd.beforeInstantiationResolved = (bean != null);
15     }
16     return bean;
17 }
18 
19 // 第8行代码如下
20 protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
21     for (BeanPostProcessor bp : getBeanPostProcessors()) {
22         if (bp instanceof InstantiationAwareBeanPostProcessor) {
23             InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
24             Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
25             if (result != null) {
26                 return result;
27             }
28         }
29     }
30     return null;
31 }
32 
33 // 第10行代码如下
34 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
35         throws BeansException {
36 
37     Object result = existingBean;
38     for (BeanPostProcessor processor : getBeanPostProcessors()) {
39         Object current = processor.postProcessAfterInitialization(result, beanName);
40         if (current == null) {
41             return result;
42         }
43         result = current;
44     }
45     return result;
46 }

第二次调用了 SmartInstantiationAwareBeanPostProcessor 的 determineCandidateConstructors 方法推断类的构造方法来实例化 Bean

 1 protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
 2     // Make sure bean class is actually resolved at this point.
 3     Class<?> beanClass = resolveBeanClass(mbd, beanName);
 4 
 5     if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
 6         throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 7                 "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
 8     }
 9 
10     Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
11     if (instanceSupplier != null) {
12         return obtainFromSupplier(instanceSupplier, beanName);
13     }
14 
15     if (mbd.getFactoryMethodName() != null) {
16         return instantiateUsingFactoryMethod(beanName, mbd, args);
17     }
18 
19     // Shortcut when re-creating the same bean...
20     boolean resolved = false;
21     boolean autowireNecessary = false;
22     if (args == null) {
23         synchronized (mbd.constructorArgumentLock) {
24             if (mbd.resolvedConstructorOrFactoryMethod != null) {
25                 resolved = true;
26                 autowireNecessary = mbd.constructorArgumentsResolved;
27             }
28         }
29     }
30     if (resolved) {
31         if (autowireNecessary) {
32             return autowireConstructor(beanName, mbd, null, null);
33         }
34         else {
35             return instantiateBean(beanName, mbd);
36         }
37     }
38     // 第二次调用后置处理器【推断构造方法来实例化 Bean】
39     /*
40      * SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
41      * Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
42      */
43     // Candidate constructors for autowiring?
44     Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
45     if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
46             mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
47         return autowireConstructor(beanName, mbd, ctors, args);
48     }
49 
50     // Preferred constructors for default construction?
51     ctors = mbd.getPreferredConstructors();
52     if (ctors != null) {
53         return autowireConstructor(beanName, mbd, ctors, null);
54     }
55 
56     // No special handling: simply use no-arg constructor.
57     return instantiateBean(beanName, mbd);
58 }
59 
60 // 第44行代码如下
61 protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
62         throws BeansException {
63 
64     if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
65         for (BeanPostProcessor bp : getBeanPostProcessors()) {
66             if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
67                 SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
68                 Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
69                 if (ctors != null) {
70                     return ctors;
71                 }
72             }
73         }
74     }
75     return null;
76 }

第三次调用了 MergedBeanDefinitionPostProcessors 的 postProcessMergedBeanDefinition 方法允许后置处理器修改合并的 BeanDefinition

1 protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
2     for (BeanPostProcessor bp : getBeanPostProcessors()) {
3         if (bp instanceof MergedBeanDefinitionPostProcessor) {
4             MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
5             bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
6         }
7     }
8 }

第四次调用了 SmartInstantiationAwareBeanPostProcessor 的 getEarlyBeanReference 方法来解决循环依赖问题

 1 protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
 2     Object exposedObject = bean;
 3     if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
 4         for (BeanPostProcessor bp : getBeanPostProcessors()) {
 5             if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
 6                 SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
 7                 exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
 8             }
 9         }
10     }
11     return exposedObject;
12 }

第五次调用 InstantiationAwareBeanPostProcessor 的 postProcessAfterInstantiation 方法判断是否需要进行属性的填充,如果需要则第六次调用后置处理器

第六次调用 InstantiationAwareBeanPostProcessor 的 postProcessPropertyValues 方法进行 Bean 属性的填充

 1 protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
 2     if (bw == null) {
 3         if (mbd.hasPropertyValues()) {
 4             throw new BeanCreationException(
 5                     mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
 6         }
 7         else {
 8             // Skip property population phase for null instance.
 9             return;
10         }
11     }
12 
13     // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
14     // state of the bean before properties are set. This can be used, for example,
15     // to support styles of field injection.
16     boolean continueWithPropertyPopulation = true;
17 
18     if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
19         for (BeanPostProcessor bp : getBeanPostProcessors()) {
20             if (bp instanceof InstantiationAwareBeanPostProcessor) {
            // 第五次调用
21 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 22 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { 23 continueWithPropertyPopulation = false; 24 break; 25 } 26 } 27 } 28 } 29 30 if (!continueWithPropertyPopulation) { 31 return; 32 } 33 34 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); 35 36 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); 37 if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 38 MutablePropertyValues newPvs = new MutablePropertyValues(pvs); 39 // Add property values based on autowire by name if applicable. 40 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { 41 autowireByName(beanName, mbd, bw, newPvs); 42 } 43 // Add property values based on autowire by type if applicable. 44 if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { 45 autowireByType(beanName, mbd, bw, newPvs); 46 } 47 pvs = newPvs; 48 } 49 50 boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); 51 boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); 52 53 PropertyDescriptor[] filteredPds = null; 54 if (hasInstAwareBpps) { 55 if (pvs == null) { 56 pvs = mbd.getPropertyValues(); 57 } 58 for (BeanPostProcessor bp : getBeanPostProcessors()) { 59 if (bp instanceof InstantiationAwareBeanPostProcessor) {
           // 第六次调用   
60 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; 61 PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); 62 if (pvsToUse == null) { 63 if (filteredPds == null) { 64 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 65 } 66 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); 67 if (pvsToUse == null) { 68 return; 69 } 70 } 71 pvs = pvsToUse; 72 } 73 } 74 } 75 if (needsDepCheck) { 76 if (filteredPds == null) { 77 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); 78 } 79 checkDependencies(beanName, mbd, filteredPds, pvs); 80 } 81 82 if (pvs != null) { 83 applyPropertyValues(beanName, mbd, bw, pvs); 84 } 85 }

第七次调用 BeanPostProcessor 的直接实现类的 postProcessBeforeInitialization 方法

第八次调用 BeanPostProcessor 的直接实现类的 postProcessAfterInitialization 方法来初始化 Bean 实例

 1 protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
 2     if (System.getSecurityManager() != null) {
 3         AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
 4             invokeAwareMethods(beanName, bean);
 5             return null;
 6         }, getAccessControlContext());
 7     }
 8     else {
 9         invokeAwareMethods(beanName, bean);
10     }
11 
12     Object wrappedBean = bean;
13     if (mbd == null || !mbd.isSynthetic()) {
14         /**
15          * 执行后置处理器 BeanPostProcessor 直接实现类的 postProcessBeforeInitialization() 方法
16          *
17          * @PostConstruct 注解是在这里面进行处理的
18          */
19         wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
20     }
21 
22     try {
23         /**
24          * 执行 Bean 生命周期回调中的 init 方法
25          *
26          * 实现 InitializingBean 接口并重写 afterPropertiesSet() 方法是在这里面进行处理的
27          */
28         invokeInitMethods(beanName, wrappedBean, mbd);
29     }
30     catch (Throwable ex) {
31         throw new BeanCreationException(
32                 (mbd != null ? mbd.getResourceDescription() : null),
33                 beanName, "Invocation of init method failed", ex);
34     }
35     if (mbd == null || !mbd.isSynthetic()) {
36         /**
37          * 执行后置处理器 BeanPostProcessor 直接实现类的 postProcessAfterInitialization() 方法
38          */
39         wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
40     }
41 
42     return wrappedBean;
43 }

第九次调用 DestructionAwareBeanPostProcessor 的 requiresDestruction 方法进行销毁工作

 1 private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) {
 2     List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
 3     if (!CollectionUtils.isEmpty(processors)) {
 4         filteredPostProcessors = new ArrayList<>(processors.size());
 5         for (BeanPostProcessor processor : processors) {
 6             if (processor instanceof DestructionAwareBeanPostProcessor) {
 7                 DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
 8                 if (dabpp.requiresDestruction(bean)) {
 9                     filteredPostProcessors.add(dabpp);
10                 }
11             }
12         }
13     }
14     return filteredPostProcessors;
15 }

至此 Spring 的 BeanFactory 就初始化完成了,分析的比较浅,也没有进行总结,后面会继续补充和完善,并辅以图表和示例代码。


原文链接:https://www.cnblogs.com/elewin/p/11316798.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:IDEA效率插件JRebel的使用

下一篇:spring4.x企业应用开发读书笔记1