Spring源码剖析-单利Bean的实例化

Posted 墨家巨子@俏如来

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring源码剖析-单利Bean的实例化相关的知识,希望对你有一定的参考价值。

前言

前面系列章节我们分析了Spring的IOC的启动流程,包括:容器创建,配置加载,配置解析,Bean注册等几个阶段,所以Bean注册其实就是把Bean的相关属性,依赖关系等封装成BeanDeafinition对象,然后注册到一个ConcurrentHashMap中。要注意的是这个BeanDeafinition只是对Bean的一个定义封装而已,并不是真正的Bean的实例,那Bean的实例是在什么时候创建的?有三种情况

  • 如果是单利Bean,且lazy-init=false 急切初始(即时,立即,迫切,饥饿都是一个意思)的情况,在IOC容器启动之后就会根据BeanDeafinition对Bean进行实例化。
  • 如果某个Bean还没被实例化,通过BeanFacotry.getBean 获取Bean的时候,就会触发Bean的实例化。
  • 通过自动注入的时候,会触发Bean的实例化

虽然有多种情况会触Bean的发实例化,但是实例化的过程都是一样的,这篇文章就讲一下IOC启动之后,单利Bean的实例化过程吧。

refresh() 单利Bean实例化

代码还得回到 AbstractApplicationContext#refresh 方法中,在《IOC启动流程》一文中我们对容器刷新refresh方法已经有过研究

@Override
   public void refresh() throws BeansException, IllegalStateException {
   	synchronized (this.startupShutdownMonitor) {
   		// Prepare this context for refreshing.
   		//准备刷新工作 ,记录开始时间,初始化属性,校验配置文件,准备事件的存储Set
   		prepareRefresh();

   		// Tell the subclass to refresh the internal bean factory.
   		//告诉子类,刷新Bean工厂,销毁旧beanFactory,创建新beanFactory,默认DefaultListableBeanFactory
   		//从子容器的refreshBeanFactory方法中载入Bean的资源文件
   		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		
        ...省略...
            
        // Instantiate all remaining (non-lazy-init) singletons.
        //实例化所有剩余的(非延迟初始化)单例的Bean
        finishBeanFactoryInitialization(beanFactory);

   		...省略...
   }

在 obtainFreshBeanFactory方法中完成了Bean的资源文件加载,Bean的解析,BeanDefinition的注册等一些列过程。最终把BeanDefinition保存到了DefaultListableBeanFactory管理的一个ConcurrentHashMap中。

我们接下来要探讨的是finishBeanFactoryInitialization; 方法,它里面实现了急切初始化的单例的Bean的创建流程。

/**
	 * Finish the initialization of this context's bean factory,
	 * initializing all remaining singleton beans.
	 * 完成此上下文的 bean 工厂的初始化,初始化所有剩余的单例 bean。
	 */
	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// Initialize conversion service for this context.
		//用于类型转换的服务接口
		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));
		}

		// Register a default embedded value resolver if no bean post-processor
		// (such as a PropertyPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}

		// Stop using the temporary ClassLoader for type matching.
		//停止使用临时类加载器进行类型匹配
		beanFactory.setTempClassLoader(null);

		// Allow for caching all bean definition metadata, not expecting further changes.
		//允许缓存所有 beandefinition 元数据,防止更改
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		//[重要]入口在这 ,实例化 lazy-init= false的单利Bean
		beanFactory.preInstantiateSingletons();
	}

这里初始化Bean Factory后,调用 beanFactory.preInstantiateSingletons 方法实例化 lazy-init= false的单利Bean, DefaultListableBeanFactory#preInstantiateSingletons源码如下:

@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		//获取到所有Bean的名字
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			//获取Bean的BeanDefinition 定义对象
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			//如果不是抽象类,如果是单利,如果lazyInit为false,触发实例化逻辑
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				//判断是否是FactoryBean
				if (isFactoryBean(beanName)) {
					//调用 getBean 方法得到FactoryBean工厂类实例。
					//【重要】getBean方法是实例化Bean的核心,后面我们要重点分析这个方法
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					//如果是FactoryBean
					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方法进行Bean的实例化
							getBean(beanName);
						}
					}
				}
				else {
					//【重要】 如果是普通的单利Bean,就调用getBean方法进行Bean的实例化
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		// 触发所有的Bean的生命周期方法的 init初始化方法.
		for (String beanName : beanNames) {
			//获取到单利Bean的实例
			Object singletonInstance = getSingleton(beanName);
			//判断Bean有没有实现 SmartInitializingSingleton接口,SmartInitializingSingleton是针对单利Bean的初始化接口
			if (singletonInstance instanceof SmartInitializingSingleton) {
				SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					//触发afterSingletonsInstantiated方法的调用
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

该方法中先是获取到IOC容器注册的所有的Bean的名字,然后循环拿到每个Bean的BeanDefinition定义对象,然后做了三个判断:不能是抽象,必须是单利,必须是急切初始化, 如果满足条件再看是普通的Bean还是FactoryBean,最终都会调用 getBean(beanName); 方法,该方法调用 AbstractBeanFactory#doGetBean 该方法创建Bean。

创建好Bean之后,会判断Bean是否实现了 SmartInitializingSingleton 初始化接口,这个是针对单利Bean的初始化接口,然后调用afterSingletonsInstantiated进行Bean的初始化。

Bean实例化流程图

先上一个流程图,待会儿你可以根据这个图来看代码。
在这里插入图片描述

AbstractBeanFactory#doGetBean

protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {
		//得到Bean的名字,如果指定的是别名,将别名转换为规范的 Bean 名称
		String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		//从缓存中获取单利的Bean,对于单利只会创建一次,创建好之后就会缓存到map中
		//默认情况下Bean都是迫切加载的,在容器启动的过程中就实例化好缓存到Map中
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isTraceEnabled()) {
				//判断bean是否在  singletonsCurrentlyInCreation set集合中,该集合中存储的是正在创建的单利Bean
				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 的相关处理
			//即:naem是是以  $ 开头 ,就返回FactoryBean工厂
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			//代码走到这里,说明单利缓存的map中是没有正在创建的bean。

			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			//如果缓存中没有单利Bean,但是缓存中有一个多利的Bean,目前正在创建,由于循环依赖问题,抛出异常
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			//得到容器IOC工厂
			BeanFactory parentBeanFactory = getParentBeanFactory();
			//通过beanName检查,如果容器中不包含这个Bean
			//如果容器中没有Bean,沿着继承体系交给父级去找
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				//得到Bean的原始名字,将别名解析为规范名称
				String nameToLookup = originalBeanName(name);
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					//根据名字,类型,参数找Bean
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
				else if (args != null) {
					//委托父工厂去找Bean , 根据名字和参数
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else if (requiredType != null) {
					// 无参数 -> 委托给标准的 getBean 方法,根据名字和类型
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
				else {
					//根据名字找Bean
					return (T) parentBeanFactory.getBean(nameToLookup);
				}
			}
			//创建Bean是否要类型检查
			if (!typeCheckOnly) {
				//标记Bean被创建
				markBeanAsCreated(beanName);
			}

			try {
				//合并Bean,主要解决Bean继承时子类和父类的公共属性
				RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				//保证当前 bean 所依赖的 bean 的初始化。
				String[] dependsOn = mbd.getDependsOn();
				//如果当前Bean依赖了其他Bean
				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);
						}
					}
				}

				// Create bean instance.
				//创建单利Bean
				if (mbd.isSingleton()) {
					//根据Bean名字获取单利Bean,这里是真正创建Bean的地方,通过ObjectFactory创建
                      //这里是匿名内部类
					sharedInstance = getSingleton(beanName, () -> {
						try {
							//创建Bean
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							//销毁实例,从缓存的map中清除单利Bean
							destroySingleton(beanName);
							throw ex;
						}
					});
					//返回bean实例,主要处理FactoryBean相关
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
				//如果是多利
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					//如果是prototype模式,每次都会创建新的实例
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						//创建指定 Bean 对象实例 ,如果是prototype模式,每次都会创建新的实例
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						//默认实现将原型标记为不再创建
						afterPrototypeCreation(beanName);
					}
					//返回bean实例,主要处理FactoryBean相关
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				else {
					String scopeName = mbd.getScope();
					//如果不是单利,不是多利,Bean没有 scope属性,则不合法
					if (!StringUtils.hasLength(scopeName)) {
						throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
					}
					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;
			}
		}
		//检查所需类型是否与实际 bean 实例的类型匹配。
		// 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;
	}

上面这个方法中代码量有点多,这里做一下总结

  • transformedBeanName(name):转换Bean的名字,如果传入的name是别名需要找到真实的Bean的名字,如果传入的name是FactoryBean,比如“&bean” ,要去掉 “&”。

  • getSingleton(name):从缓存中查找Bean(ConcurrentHashMap中),单利Bean只会在容器中创建一次,后续都从缓存中加载,如果缓存中没有就就会进行创建。默认情况下Bean都是迫切创建的,即在容器启动的过程中就会根据BeaDefinition创建好Bean的实例存储到缓存中。
    在创建单利Bean的时候会存在依赖注入的情况,为了解决循环依赖(A依赖B,B依赖A),在创建Bean的时候会提前将ObjectFactory 加入缓存,如果下个Bean创建时需要依赖上一个Bean就会直接使用ObejctFactory(后面讲循环依赖)

  • createBean :Bean的实例化,从BeanDefinition的缓存中获取当前Bean的BeanDefinition定义对象,根据BeanDefinition进行Bean的创建。如果是通过工厂Bea 方式实例化,则需要得到工厂Bean中的factory-method方法返回的的Bean的实例,通过getObjectForBeanInstance 处理的。

  • isPrototypeCurrentlyInCreation:Prototype依赖检查,单利情况下才会解决循环依赖,如果A中依赖了B,B中依赖了A,在创建依赖的时候就会产生循环依赖。

  • 如果是多利Bean直接走createBean创建一个新的Bean

DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory)

对于 getSingleton从缓存中获取单利Bean的方法,这里有两个重载方法第一个方法是在 Object sharedInstance = getSingleton(beanName);
时候调用,源码如下:

//allowEarlyReference :是否创建早期应用,主要用来解决循环依赖
	@Nullable
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		// Quick check for existing instance without full singleton lock
		//从Map中 singletonObjects = new ConcurrentHashMap<>(256); 获取单利Bean
		
		//singletonObject缓存中是否有Bean
		Spring系列(一)Spring MVC bean 解析、注册、实例化流程源码剖析

Spring源码剖析-Bean的实例化-属性注入

看看Spring的源码——bean实例化

Spring源码分析非懒加载的Bean实例化过程(下篇)

spring 中单利模式的理解

Spring源码剖析1:初探Spring IOC核心流程