spring源码学习(5.1.0)——Bean的初始化(下)

目录

 

 

前言

populateBean

autowireByName

autowireByType

resolveDependency

doResolveDependency

applyPropertyValues

initializeBean

结语


 

前言

上篇博客主要介绍了createBean方法,Bean的初始化会有三个主要的方法

createBean:初始化Bean,此时还没有进行属性填充
populateBean:进行属性填充
initializeBean:调用生命周期回调
这篇博客主要介绍populateBean、initializeBean方法

本文难免有错误,欢迎大家指出错误
 

populateBean

	/**
	 * Populate the bean instance in the given BeanWrapper with the property values
	 * from the bean definition.
	 * @param beanName the name of the bean
	 * @param mbd the bean definition for the bean
	 * @param bw the BeanWrapper with bean instance
	 */
	@SuppressWarnings("deprecation")  // for postProcessPropertyValues
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			bw为空,说明Bean是一个空对象,空对象却有需要填充的属性,抛出异常
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				跳过空对象
				return;
			}
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		boolean continueWithPropertyPopulation = true;

		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					postProcessAfterInstantiation(java.lang.Object bean, java.lang.String beanName)返回对象的类型为Object
					如果该方法返回为null,说明是空对象,就不需要继续进行属性填充
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}

		pvs存储setter依赖注入的属性的值,第一次初始化时,pvs的值为null
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		setter依赖注入有两种方式:
		1、根据Bean的名字
		2、根据Bean的类型
		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			通过上面两个方法,pvs存储了setter依赖注入的属性的值
			pvs = newPvs;
		}

		确保存在InstantiationAwareBeanPostProcessor类的实例
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		判断是否需要依赖检查
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
				如果pvs为空,尝试从RootBeanDefinition中获取
				if (pvs == null) {
					pvs = mbd.getPropertyValues();
				}
				获得过滤条件,过滤一部分依赖
				PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
				if (hasInstAwareBpps) {
					for (BeanPostProcessor bp : getBeanPostProcessors()) {
						if (bp instanceof InstantiationAwareBeanPostProcessor) {
							InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
							/*Post-process the given property values before the factory applies them to the given bean.
							*Allows for checking whether all dependencies have been satisfied, 
							*for example based on a "Required" annotation on bean property setters.
							*Also allows for replacing the property values to apply, 
							*typically through creating a new MutablePropertyValues instance based on the original PropertyValues, 
							*adding or removing specific values.
							*/
							pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
							if (pvs == null) {
								return;
							}
						}
					}
				}
				
				if (needsDepCheck) {
					依赖检查,以确定所有所需依赖都已经初始化
					checkDependencies(beanName, mbd, filteredPds, pvs);
				}
			}
		}
		if (pvs != null) {
			这里会将依赖注入到对应的属性中
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

接下来看看自动装配相关的两个方法

autowireByName

	/**
	 * Fill in any missing property values with references to
	 * other beans in this factory if autowire is set to "byName".
	 * @param beanName the name of the bean we're wiring up.
	 * Useful for debugging messages; not used functionally.
	 * @param mbd bean definition to update through autowiring
	 * @param bw the BeanWrapper from which we can obtain information about the bean
	 * @param pvs the PropertyValues to register wired objects with
	 */
	protected void autowireByName(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		获得需要进行依赖注入的属性
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			确保容器含有这个Bean的BeanDefinition
			if (containsBean(propertyName)) {
				调用getBean函数,获得实例,若依赖还没有初始化,则在这里会初始化
				由于当前Bean已经存在于三级缓存,所以可以处理setter循环依赖的情况
				Object bean = getBean(propertyName);
				添加到pvs缓存中,以便applyPropertyValues函数进行依赖注入
				pvs.add(propertyName, bean);
				存储beanName与propertyName的依赖关系,这里会做两件事
				1、记录beanName依赖于propertyName
				2、记录propertyName是beanName的依赖,以便销毁propertyName实例时,首先销毁beanName实例
				registerDependentBean(propertyName, beanName);
				if (logger.isTraceEnabled()) {
					logger.trace("Added autowiring by name from bean name '" + beanName +
							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
				}
			}
		}
	}

autowireByType

	/**
	 * Abstract method defining "autowire by type" (bean properties by type) behavior.
	 * <p>This is like PicoContainer default, in which there must be exactly one bean
	 * of the property type in the bean factory. This makes bean factories simple to
	 * configure for small namespaces, but doesn't work as well as standard Spring
	 * behavior for bigger applications.
	 * @param beanName the name of the bean to autowire by type
	 * @param mbd the merged bean definition to update through autowiring
	 * @param bw the BeanWrapper from which we can obtain information about the bean
	 * @param pvs the PropertyValues to register wired objects with
	 */
	protected void autowireByType(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		获得类型转换器,用于类型转换,spring预先定义了一堆类型转换器,springmvc的handlerAdapter中就有用到spring定义的转换器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}

		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		获得需要依赖的属性
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			try {
				尝试获得缓存,由于是第一次初始化,所以pd一定为null
				PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
				// Don't try autowiring by type for type Object: never makes sense,
				// even if it technically is a unsatisfied, non-simple property.
				不会为类型为object的属性进行依赖注入,因为所有的Bean都满足,肯定会出现冲突
				if (Object.class != pd.getPropertyType()) {
					获得对应属性的setter方法的形参
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					
					boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					根据类型从容器获得对应的依赖,如果有多个Bean满足条件
					则会根据一系列规则,保证只返回一个依赖
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					if (autowiredArgument != null) {
						添加到pvs缓存中,以便applyPropertyValues函数进行依赖注入
						pvs.add(propertyName, autowiredArgument);
					}
					for (String autowiredBeanName : autowiredBeanNames) {
						存储beanName与propertyName的依赖关系,这里会做两件事
						1、记录beanName依赖于propertyName
						2、记录propertyName是beanName的依赖,以便销毁propertyName实例时,首先销毁beanName实例
						registerDependentBean(autowiredBeanName, beanName);
						if (logger.isTraceEnabled()) {
							logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
									propertyName + "' to bean named '" + autowiredBeanName + "'");
						}
					}
					autowiredBeanNames.clear();
				}
			}
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
			}
		}
	}

重点在于如何根据类型获得依赖——resolveDependency

resolveDependency

	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
		
		getDependencyType会调用 Field.getGenericType获取成员变量声明类型(包含泛型类型)
        java.util.Optional类型
		if (Optional.class == descriptor.getDependencyType()) {
			将 doResolveDependency返回包装成 Optional
			return createOptionalDependency(descriptor, requestingBeanName);
		}
		
		处理ObjectFactory或 ObjectProvider类型
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
			return new DependencyObjectProvider(descriptor, requestingBeanName);
		}
		
		处理javax.inject.Provider类型
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
		}
		else {
		
			ContextAnnotationAutowireCandidateResolver实现了 getLazyResolutionProxyIfNecessary
			对于被 @Lazy标识的成员,通过代理支持延迟加载,用于处理生命周期不一致的情况
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {
				一般情况下,会跑到这里来获得对应属性,展开此方法
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
			}
			return result;
		}
	}

doResolveDependency

	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
			resolveShortcut函数由ShortcutDependencyDescriptor实现,该方法尝试通过getBean(String name, Class<T> requiredType)
			方法获得实例
			Object shortcut = descriptor.resolveShortcut(this);
			if (shortcut != null) {
				return shortcut;
			}

			获得依赖的类型
			Class<?> type = descriptor.getDependencyType();
			处理@Value注解
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
			if (value != null) {
				if (value instanceof String) {
					对@value注解的值进行处理
					String strVal = resolveEmbeddedValue((String) value);
					BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
					value = evaluateBeanDefinitionString(strVal, bd);
				}
				获得类型转换器
				TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
				依据属性的类型对@Value注解的值进行类型转换
				return (descriptor.getField() != null ?
						converter.convertIfNecessary(value, type, descriptor.getField()) :
						converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
			}
			
			resolveMultipleBeans函数干了下面几件事
			1、如果是数组,则获取数组元素类型,查找匹配该类型的所有bean,返回一个这些bean的数组;
			2、如果该类可赋给Collection,并且是一个接口,则获取集合元素类型,查找匹配该类型的所有bean,返回一个这些bean的集合;
			3、如果该类型是Map(注意是type == Map.class),且key是String类型,则获取Map的value的类型,
			   查找匹配该类型的所有bean,这是一个key为bean name、value为bean实例的一个Map,返回这个Map。
			4、容器中所有的实例都会缓存到autowiredBeanNames中,用于记录Bean与Bean之间的依赖关系
			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			if (multipleBeans != null) {
				return multipleBeans;
			}

			依据类型获得所有满足条件的bean
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (matchingBeans.isEmpty()) {
				如果没有满足条件的bean,则判断是不是有@Require注解,这几行代码说明,没有找到依赖的情况下
				默认情况下,对应的bean属性为null
				if (isRequired(descriptor)) {
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				return null;
			}

			String autowiredBeanName;
			Object instanceCandidate;

			如果有多个满足条件的bean
			if (matchingBeans.size() > 1) {
				1、通过primary属性来判断,多个同类型 bean同时配置 primary会抛异常
                2、如果上面没结果,则通过@Priority注解来筛选
                3、依旧没有结果,通过候选名称与成员定义的 beanName/别名匹配(对于按类型匹配来说,这个默认不成立)
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				if (autowiredBeanName == null) {
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
						由于resolveMultipleBeans函数需要满足一定条件才能进行匹配,所以走到这一步,依赖的类型仍然可能是容器
						如果bean的属性有@Require注解修饰或者不是数组、collection、map类型,则抛 NoUniqueBeanDefinitionException异常
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
					}
					else {
						// In case of an optional Collection/Map, silently ignore a non-unique case:
						// possibly it was meant to be an empty collection of multiple regular beans
						// (before 4.3 in particular when we didn't even look for collection beans).
						对于容器类型来说,如果不满足resolveMultipleBeans函数的匹配条件,即使有多个匹配bean,也会返回null
						return null;
					}
				}
				instanceCandidate = matchingBeans.get(autowiredBeanName);
			}
			else {
				// We have exactly one match.
				只有一个匹配结果的情况
				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) {
				如果是class对象,则对其进行实例化
				instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
			}
			Object result = instanceCandidate;
			if (result instanceof NullBean) {
				if (isRequired(descriptor)) {
				这里还要判断一次,是因为NullBean也是一个类,也可能满足类型匹配,
				但是这个类表示null,如果属性有@Require注解修饰,抛出异常,
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				result = null;
			}
			if (!ClassUtils.isAssignableValue(type, result)) {
				throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
			}
			return result;
		}
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
		}
	}

这个方法还可以继续展开,但碍于精力有限,过一段时间在看,主要是类型匹配相关的方法:

1、findAutowireCandidates(beanName, type, descriptor)
2、resolveShortcut函数由ShortcutDependencyDescriptor实现,该方法尝试通过getBean(String name, Class<T> requiredType)
    方法获得实例
    bject shortcut = descriptor.resolveShortcut(this);
3、resolveMultipleBeans函数

applyPropertyValues

	/**
	 * Apply the given property values, resolving any runtime references
	 * to other beans in this bean factory. Must use deep copy, so we
	 * don't permanently modify this property.
	 * @param beanName the bean name passed for better exception information
	 * @param mbd the merged bean definition
	 * @param bw the BeanWrapper wrapping the target object
	 * @param pvs the new property values
	 */
	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		pvs为空,没有需要setter依赖注入的属性,返回
		if (pvs.isEmpty()) {
			return;
		}

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

		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;

		MutablePropertyValues是一个容器,实现了PropertyValues接口,用于存储setter依赖注入的属性以及对应的值
		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			mpvs.isConverted用于判断容器中的属性值是否进行了类型转换
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					如果进行了类型转换,直接进行setter依赖注入,然后返回
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			original = mpvs.getPropertyValueList();
		}
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		}

		经过上述操作,original中保存了所有属性以及对应的值
		
		获得类型转换器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		// Create a deep copy, resolving any references for values.
		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();
				以下这句代码用C++来说,就是将指针指向某一个对象,官方文档的解释是:
				Given a PropertyValue, return a value, resolving any references to other beans in the factory if necessary. The value could be:
				1、A BeanDefinition, which leads to the creation of a corresponding new bean instance. Singleton flags and names of such "inner beans" are always ignored: Inner beans are anonymous prototypes.
				2、A RuntimeBeanReference, which must be resolved.
				3、A ManagedList. This is a special collection that may contain RuntimeBeanReferences or Collections that will need to be resolved.
				4、A ManagedSet. May also contain RuntimeBeanReferences or Collections that will need to be resolved.
				5、A ManagedMap. In this case the value may be a RuntimeBeanReference or Collection that will need to be resolved.
				   An ordinary object or null, in which case it's left alone.

				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				
				对属性进行类型转换的条件
				1、属性可写
				2、非指示索引,即person.addresses[0]
				3、非嵌套属性,即foo.bar
				2与3出现在xml配置中
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					进行类型转换,对象的存储结构可能会发生变化,需要看一看convertForProperty
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				
				
				经过上述操作,所有的类型都进行了类型转换,接下来将它们存储到BeanDefinition中,
				以便下次初始化时,不需要再次进行类型转换
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				没有进行类型转换
				if (resolvedValue == originalValue) {
					if (convertible) {
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				进行了类型转换,满足下列条件时,存储到BeanDefinition中:
				1、convertible为true(看上文的条件)
				2、originalValue继承了TypeStringValue(这个类内部存储了源对象以及类型转换后的对象(或类型))
				3、该对象非动态,关于什么是动态,源码中是这么解释的:as containing an expression and hence not being subject to caching.
				   我的理解是含有spring EL
				4、转换后的类型不是集合、数组类型,为什么数组、集合类型不缓存呢?
				   我的理解是每次实例化时,集合以及数组中的成员都可能发生变化
				  (例如scope为原型的对象,可能实例化多次,而且scope为原型的对象生命周期不受容器控制),故不缓存
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				不满足if、else if中的条件,则不存储到BeanDefinition中
				else {
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		if (mpvs != null && !resolveNecessary) {
			设置以进行类型转换标志,下次初始化时,就不需要在进行类型转换
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
			设置属性值
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}
}
	

上述代码提到了类型转换,这种类型转换并不是子类与父类之间的转换,而是不同存储结构的类之间的转换,例如将Date转换为Calender,spring定义了许多类型转换器,springmvc就是利用spring的类型转换器实现http与java对象的相互转换的,spring的类型转换器非常的多,这里就不一一列举了

至此,对象的依赖注入就完成了,接下来,进行生命周期回调,为需要生成代理的对象生成代理

initializeBean

	/**
	 * Initialize the given bean instance, applying factory callbacks
	 * as well as init methods and bean post processors.
	 * <p>Called from {@link #createBean} for traditionally defined beans,
	 * and from {@link #initializeBean} for existing bean instances.
	 * @param beanName the bean name in the factory (for debugging purposes)
	 * @param bean the new bean instance we may need to initialize
	 * @param mbd the bean definition that the bean was created with
	 * (can also be {@code null}, if given an existing bean instance)
	 * @return the initialized bean instance (potentially wrapped)
	 * @see BeanNameAware
	 * @see BeanClassLoaderAware
	 * @see BeanFactoryAware
	 * @see #applyBeanPostProcessorsBeforeInitialization
	 * @see #invokeInitMethods
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			设置BeanDefiniton中的部分值
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
		调用BeanPostProcessorsBeforeInitialization,在调用init函数之前对bean进行处理
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			调用init函数,这个方法内部会通过解析得到需要执行的init函数
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			调用BeanPostProcessorsAfterInitialization,此处会为需要生成代理的对象生成代理
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

结语

至此,spring的IOC容器的初始化的粗略框架就总结完了,看完这些代码,再来看看什么是IOC,简单来说,IOC就是一个缓存,可以缓存spring创建的实例,并且,IOC能帮助我们创建Bean,并管理单例Bean的生命周期,非单例Bean由于不会被spring缓存,spring自然就不会管理其生命周期

猜你喜欢

转载自blog.csdn.net/dhaiuda/article/details/83743267