转载

Spring源码(三)SpringIOC初始化过程-完成Bean的初始化

在上一篇中已经讲解完**invokeBeanFactoryPostProcessors(beanFactory);**方法;我们看看下面还有什么方法

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		//准备工作包括设置启动时间,是否激活标识位,
		// 初始化属性源(property source)配置
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		//返回一个factory 为什么需要返回一个工厂
		//因为要对工厂进行初始化 
           /** 这里说明一下:如果你使用是的xml配置的方式就会执行				  AbstractRefreshableApplicationContext的refreshBeanFactory方法去加载xml配置信息;因为ClassPathXmlApplicationContext是它的子类;现在我们使用的是注解配置的方式所以会执行GenericApplicationContext的refreshBeanFactory方法,这个方法就是只返回了一个beanFactory**/
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		//准备工厂
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.

			//这个方法在当前版本的spring是没用任何代码的
			//可能spring期待在后面的版本中去扩展吧
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			//在spring的环境中去执行已经被注册的 factory processors
			//设置执行自定义的ProcessBeanFactory 和spring内部自己定义的
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			//注册beanPostProcessor
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			// 初始化当前 ApplicationContext 的 MessageSource,国际化这里就不展开说了
			initMessageSource();

			// Initialize event multicaster for this context.
			//初始化应用事件广播器
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			// 从方法名就可以知道,典型的模板方法(钩子方法),
			// 具体的子类可以在这里初始化一些特殊的 Bean(在初始化 singleton beans 之前)
			onRefresh();

			// Check for listener beans and register them.
			// 注册事件监听器,监听器需要实现 ApplicationListener 接口。这也不是我们的重点,过
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			// 重点,重点,重点
			// 初始化所有的 singleton beans
			//(lazy-init 的除外)
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			// 最后,广播事件,ApplicationContext 初始化完成
			finishRefresh();
		}
           //.......
复制代码

国际化初始化应用事件广播器 , 注册事件监听 在这里就不过多的阐述了,要不然真的是没完没了了;我们重点看下初始化所有的 singleton beans方法;

初始化所有的 singleton beans -finishBeanFactoryInitialization(beanFactory);

**finishBeanFactoryInitialization(beanFactory);**方法除了懒加载之外的beans,在这里都会进行初始化;

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// 首先,初始化名字为 conversionService 的 Bean。这里不是重点
		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);

		// 这里将beanDefinitionNames赋值给frozenBeanDefinitionNames
		//目的就是到了这一步,Spring 已经开始预初始化 singleton beans 了,
		// 不能再出现其他的 bean 定义解析、加载、注册了;
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		//实例化所有的单例对象
		beanFactory.preInstantiateSingletons();
	}
复制代码

重点是preInstantiateSingletons();方法:

public void preInstantiateSingletons() throws BeansException {
		if (logger.isDebugEnabled()) {
			logger.debug("Pre-instantiating singletons in " + this);
		}
		//所有bean的名字
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		// 触发所有非延迟加载单例beans的初始化,主要步骤为调用getBean
		for (String beanName : beanNames) {
			//合并父BeanDefinition
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			//是否为抽象类,是否是单例,是否是懒加载
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				//是否是FactoryBean,这里肯定是不,后续文章会讲到FactoryBean和BeanFactory的区别
				if (isFactoryBean(beanName)) {
					//如果是FactoryBean则加上&
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						final 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 {
					//不是FactoryBean直接到这个方法中
					getBean(beanName);
				}
			}
		}

		// 到这里说明所有的非懒加载的 singleton beans 已经完成了初始化
		// 如果我们定义的 bean 是实现了 SmartInitializingSingleton 接口的,那么在这里得到回调,忽略
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

复制代码

重点到getBean(beanName)方法中;而初始化的过程也封装到了这个方法里。

public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}
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, bean>,beanName 中是没有 & 这个字符的。所以我们需要
		 *   将 name 的首字符 & 移除,这样才能获取到一个传统的Bean
		 * 2、还是别名的问题,转换需要
		 * &beanName
		 */
		final String beanName = transformedBeanName(name);
        //这个是返回值
		Object bean;

		 /**
			 * 这个方法在初始化的时候会调用,在getBean的时候也会调用
			 * 为什么需要这么做呢?
			 * 也就是说spring在初始化的时候先获取这个对象
			 * 判断这个对象是否被实例化好了
			 * 在初始化时候调用一般都是返回null
			 */
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					//log.....
				}
				else {
					//log.....
				}
			}
            /**
			 * 如果 sharedInstance 是普通的单例 bean,下面的方法会直接返回。但如果
			 * sharedInstance 是 FactoryBean 类型的,则需调用 getObject 工厂方法获取真正的
			 * bean 实例。如果用户想获取 FactoryBean 本身,这里也不会做特别的处理,直接返回
			 * 即可。毕竟 FactoryBean 的实现类本身也是一种 bean,只不过具有一点特殊的功能而已。
			 */
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// 检查原型的bean是否再创建中,如果已经在创建中就抛出异常
            //一般是陷入了循环依赖
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// 检查一下这个 Bean Definition 在工厂中是否存在
			BeanFactory parentBeanFactory = getParentBeanFactory();//null
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
                // 如果当前容器不存在这个 BeanDefinition,试试父容器中有没有
				String nameToLookup = originalBeanName(name);
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
                //args 是上面传过来的null
				else if (args != null) {
					// 返回父容器的查询结果
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					// No args -> 委托给标准的getBean方法。
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}
			//因为上面parentBeanFactory==null,代码来到这里
			if (!typeCheckOnly) {
                //将beanName添加到alreadyCreated set集合当中
				markBeanAsCreated(beanName);
			}
		/*
       	 * 稍稍总结一下:
       	 * 到这里的话,要准备创建 Bean 了,对于 singleton 的 Bean 来说,容器中还没创建过此 Bean;
         * 对于 prototype 的 Bean 来说,本来就是要创建一个新的 Bean。
       */
			try {
                 // 从容器中获取 beanName 相应的 GenericBeanDefinition,并将其转换为 RootBeanDefinition
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                // 检查给定的合并的 BeanDefinition
				checkMergedBeanDefinition(mbd, beanName, args);
				//检查dependes-on依赖
				// 先初始化依赖的所有 Bean
              // 注意,这里的依赖指的是 depends-on 中定义的依赖
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
                     //获取depends-on的属性值,如果depends-on的值存在 则添加进入dependentBeanMap缓存中
					for (String dep : dependsOn) {
						if (isDependent(beanName, dep)) {
							throw new BeanCreationException(....);
						}
                        // 注册一下依赖关系
						registerDependentBean(dep, beanName);
						try {
                            // 先初始化被依赖项
							getBean(dep);
						}
						catch (NoSuchBeanDefinitionException ex) {
							throw new BeanCreationException(...);
						}
					}
				}

				// 创建bean实例.
				if (mbd.isSingleton()) {
                    //jdk1.8 Lambda表达式,这里调用的是getSingleton方法中的getObject方法;
					sharedInstance = getSingleton(beanName, () -> {
						try {
                            // 执行创建 Bean
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
				 // 如果是 prototype scope 的,创建 prototype 的实例
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
                        // 执行创建 Bean
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}
			// 如果不是 singleton 和 prototype 的话,需要委托给相应的实现类来处理
				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 {
                                // 执行创建 Bean
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(...)....
								
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// 最后,检查一下类型对不对,不对的话就抛异常,对的话就返回了.
		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.isDebugEnabled()) {
					//log....
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}
复制代码

在上面这个方法中源码大概实在315行左右,涉及到jdk1.8新特新Lambda表达式getSingleton();在这个方法中调用了getObject()方法;进入getSingleton()方法中简单看下:

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(beanName, "Bean name must not be null");
		synchronized (this.singletonObjects) {
            //当前beanName IndexDaoImpl还没有放入singletonObjects中,所以这里是null
			Object singletonObject = this.singletonObjects.get(beanName);
			if (singletonObject == null) {
                //检查是否在销毁,如果在销毁就抛出异常
				if (this.singletonsCurrentlyInDestruction) {
					throw new BeanCreationNotAllowedException(.....);
				}
				//log.....
				/**
				 * 将beanName添加到singletonsCurrentlyInCreation这样一个set集合中
				 * 表示beanName对应的bean正在创建中
				 */
				beforeSingletonCreation(beanName);
				boolean newSingleton = false;
				boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
				if (recordSuppressedExceptions) {
					this.suppressedExceptions = new LinkedHashSet<>();
				}
				try {
                    //调用getObject()方法,这个方法其实就是调用上面Lambda表达式中那个createBean()
					singletonObject = singletonFactory.getObject();
					newSingleton = true;
				}
				catch (IllegalStateException ex) {
					//.......
                    throw ex;
				}
				catch (BeanCreationException ex) {
					//.......
					throw ex;
				}
				finally {
					if (recordSuppressedExceptions) {
						this.suppressedExceptions = null;
					}
                    //把标识为正在创建的标识去掉
					afterSingletonCreation(beanName);
				}
				if (newSingleton) {
                    //向集合中添加数据
                 /**
				 * protected void addSingleton(String beanName, Object singletonObject) {
				 * 		synchronized (this.singletonObjects) {
				 * 			this.singletonObjects.put(beanName, singletonObject);
				 * 			this.singletonFactories.remove(beanName);
				 * 			this.earlySingletonObjects.remove(beanName);
				 * 			this.registeredSingletons.add(beanName);
				 *      }
				  */
					addSingleton(beanName, singletonObject);
				}
			}
			return singletonObject;
		}
	}
复制代码

我们接下来看看getObject()方法,上面注释也说到了getObject()方法中其实就在调用createBean()

接下来我们重点分析一下 createBean() 方法;

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
复制代码

第三个参数 args 数组代表创建实例需要的参数,不就是给构造方法用的参数,或者是工厂 Bean 的参数嘛,不过要注意,在我们的初始化阶段,args 是 null。

看类名我们到了一个新的类 AbstractAutowireCapableBeanFactory,主要是为了 @Autowired 注解注入属性值

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

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

	 // 确保 BeanDefinition 中的 Class 被加载
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.
		try {
       // 处理 lookup-method 和 replace-method 配置,Spring 将这两个配置统称为 override method
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(...);
		}

		try {
			// 在 bean 初始化前应用后置处理,如果后置处理返回的 bean 不为空,则直接返回
			//这个类需要通过代码演示
           //这里执行了bean=applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);  在AOP中使用到可以返回一个代理对象
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(.....);
		}

		try {
            // 重头戏
			// 调用doCreateBean 创建bean  
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			//log.....
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(......);
		}
	}
复制代码

我们继续向doCreateBean()方法中看:

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

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			/**
			 * 创建 bean 实例,并将实例包裹在 BeanWrapper 实现类对象中返回。
			 * createBeanInstance中包含三种创建 bean 实例的方式:
			 *   1. 通过工厂方法创建 bean 实例
			 *   2. 通过构造方法自动注入(autowire by constructor)的方式创建 bean 实例
			 *   3. 通过无参构造方法方法创建 bean 实例
			 *
			 * 若 bean 的配置信息中配置了 lookup-method 和 replace-method,则会使用 CGLIB
			 * 增强 bean 实例。关于lookup-method和replace-method后面再说。
			 */
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// 建议跳过吧,涉及接口:MergedBeanDefinitionPostProcessor
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		// 下面这块代码是为了解决循环依赖的问题;后续文章会讲解到
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				//log....
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			//设置属性,非常重要
       // 这一步负责属性装配,因为前面的实例只是实例化了,并没有设值,这里就是设值
			populateBean(beanName, mbd, instanceWrapper);
			//执行后置处理器,aop就是在这里完成的处理
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}

		//......省略了一些不重要的代码

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(.....);
		}

		return exposedObject;
	}
复制代码

上面这段代码重点方法是createBeanInstance();

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// 确保已经加载了此 class
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		/**
		 * 检测一个类的访问权限spring默认情况下对于非public的类是允许访问的。
		 */
		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}

		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}

		/**
		 *
		 * 如果工厂方法不为空,则通过工厂方法构建 bean 对象
		 * 这种构建 bean 的方式可以自己写个demo去试试
		 * 源码就不做深入分析了,有兴趣的同学可以和我私下讨论
		 */
		if (mbd.getFactoryMethodName() != null)  {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		/**
		 * 从spring的原始注释可以知道这个是一个Shortcut,什么意思呢?
		 * 当多次构建同一个 bean 时,可以使用这个Shortcut,
		 * 也就是说不在需要每次推断应该使用哪种方式构造bean
		 *  比如在多次构建同一个prototype类型的 bean 时,就可以走此处的Shortcut
		 * 这里的 resolved 和 mbd.constructorArgumentsResolved 将会在 bean 第一次实例
		 * 化的过程中被设置;
		 */
		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) {
				// 通过构造方法自动装配的方式构造 bean 对象
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				//通过默认的无参构造方法进行
				return instantiateBean(beanName, mbd);
			}
		}

		// Candidate constructors for autowiring?
		//由后置处理器决定返回哪些构造方法
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// No special handling: simply use no-arg constructor.
		//使用默认的无参构造方法进行初始化
		return instantiateBean(beanName, mbd);
	}
复制代码

我们看看无参构造是怎么实例化对象的

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
		try {
			Object beanInstance;
			final BeanFactory parent = this;
			if (System.getSecurityManager() != null) {
				beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
						getInstantiationStrategy().instantiate(mbd, beanName, parent),
						getAccessControlContext());
			}
			else {
				//getInstantiationStrategy()得到类的实例化策略
				//默认情况下是得到一个反射的实例化策略
				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
			}
			//包装一下进行返回
			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
			initBeanWrapper(bw);
			return bw;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
		}
	}
复制代码

关键代码在:

beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);

得到反射的实例化策略之后进入instantiate方法:

public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		//检测 bean 配置中是否配置了 lookup-method 或 replace-method
		//如果配置了就需使用 CGLIB 构建 bean 对象
		if (!bd.hasMethodOverrides()) {
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
					final Class<?> clazz = bd.getBeanClass();
					if (clazz.isInterface()) {
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(
									(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
						}
						else {
							//得到无参构造
							constructorToUse =	clazz.getDeclaredConstructor();
						}
						//在这里给resolvedConstructorOrFactoryMethod赋了值
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Throwable ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			//实例化
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}
复制代码

进入instantiateClass方法进行实例化:

public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
		Assert.notNull(ctor, "Constructor must not be null");
		try {
			// 设置构造方法为可访问
			ReflectionUtils.makeAccessible(ctor);
			//反射创建对象
			return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
					KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
		}
复制代码

这里就比较简单了就是使用反射ctor.newInstance(args)进行实例化;这里拿到实例化之后的Bean返回到:

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

中设置属性,处理依赖

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
   // bean 实例的所有属性都在这里了
   PropertyValues pvs = mbd.getPropertyValues();

   if (bw == null) {
      if (!pvs.isEmpty()) {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      }
      else {
         // Skip property population phase for null instance.
         return;
      }
   }

   // 到这步的时候,bean 实例化完成(通过工厂方法或构造方法),但是还没开始属性设值,
   // InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改,
   // 我也没找到有实际的使用,所以我们暂且忽略这块吧
   boolean continueWithPropertyPopulation = true;
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            // 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               continueWithPropertyPopulation = false;
               break;
            }
         }
      }
   }

   if (!continueWithPropertyPopulation) {
      return;
   }

   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
         mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

      // 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }

      // 通过类型装配。复杂一些
      if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }

      pvs = newPvs;
   }

   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

   if (hasInstAwareBpps || needsDepCheck) {
      PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      if (hasInstAwareBpps) {
         for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
               InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
               // 这里有个非常有用的 BeanPostProcessor 进到这里: AutowiredAnnotationBeanPostProcessor
               // 对采用 @Autowired、@Value 注解的依赖进行设值,这里的内容也是非常丰富的,不过本文不会展开说了,感兴趣的读者请自行研究
               pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvs == null) {
                  return;
               }
            }
         }
      }
      if (needsDepCheck) {
         checkDependencies(beanName, mbd, filteredPds, pvs);
      }
   }
   // 设置 bean 实例的属性值
   applyPropertyValues(beanName, mbd, bw, pvs);
}
复制代码

属性注入完成后,紧接着就是处理各种回调:

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 {
      // 如果 bean 实现了 BeanNameAware、BeanClassLoaderAware 或 BeanFactoryAware 接口,回调
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			//执行后置处理的befor
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			//执行bean的声明周期回调中的init方法
      // 或者如果 bean 实现了 InitializingBean 接口,调用 afterPropertiesSet() 方法
			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()) {
			//执行后置处理器的after方法
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
复制代码

BeanPostProcessor 的两个回调都发生在这边,只不过中间处理了 init-method

到这里整个初始化过程就讲解完了;下面画个图讲解一下finishBeanFactoryInitialization方法的整个过程:

因为图片有点大,我把大缩小了,如果觉得图片看不清,可以把地址抠出来,在浏览器中看;

Spring源码(三)SpringIOC初始化过程-完成Bean的初始化
带中文注释的Spring源码

,

博客总结

使用博客观看效果更佳

原文  https://juejin.im/post/5de4afc16fb9a071a828ff13
正文到此结束
Loading...