spring-boot bean初始化源码分析(二)

在上一篇spring-boot bean初始化源码分析(一)最后我们已经把被@Component注解的类和classpath下"META-INF/spring-autoconfigure-metadata.properties文件中的类添加到了beanFactory中(例如beanDefinitionMap、beanDefinitionNames),今天我们再来看一下是如果把上面放到beanFactory中BeanDefinition对象实例化的。

/**
 * AbstractApplicationContext
 */
public void refresh() throws BeansException, IllegalStateException {
	......
	// 实例化余下所有非懒加载的singletons
	finishBeanFactoryInitialization(beanFactory);
	......
}

/**
 * AbstractApplicationContext
 */
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	......
	// Instantiate all remaining (non-lazy-init) singletons.
	beanFactory.preInstantiateSingletons();
}

/**
 * DefaultListableBeanFactory
 */
@Override
public void preInstantiateSingletons() throws BeansException {
	
	// 遍历beanDefinitionNames集合中的BeanDefinition
	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

	for (String beanName : beanNames) {
		// 根据beanName从beanDefinitionNames集合中查询BeanDefinition
		// 将非RootBeanDefinition类型的转化为这种类型,并添加到mergedBeanDefinitions集合
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		// 如果该beanDefinition是单例,非懒加载模式的非抽象类,就实例化
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			// 判断Bean是否实现了FactoryBean接口,如果实现了进一步判断是否需要初始化
			if (isFactoryBean(beanName)) {
				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);
					}
				}
			}
			// 如果没有实现FactoryBean就直接初始化
			else {
				getBean(beanName);
			}
		}
	}

	// 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();
			}
		}
	}
}

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

	// 如果是FactoryBean,就去掉开头的&
	// 可能存在别名多层映射的情况,返回最原始的beanName
	final String beanName = transformedBeanName(name);
	Object bean;

	// 先尝试从singletonObjects缓存中获取,获取不到再走创建流程
	Object sharedInstance = getSingleton(beanName);
	if (sharedInstance != null && args == null) {
		// 处理FactoryBean情况,如果实现了FactoryBean接口,就调用getObject方法去获取实际的Bean实例
		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
	}

	else {
		// 如果原型对象正在创建,就抛异常
		if (isPrototypeCurrentlyInCreation(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}

		// 如果当前容器不存在,且存在父容器,就用父容器去实例化
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// Not found -> check parent.
			String nameToLookup = originalBeanName(name);
			if (parentBeanFactory instanceof AbstractBeanFactory) {
				return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
						nameToLookup, requiredType, args, typeCheckOnly);
			}
			else if (args != null) {
				// Delegation to parent with explicit args.
				return (T) parentBeanFactory.getBean(nameToLookup, args);
			}
			else {
				// No args -> delegate to standard getBean method.
				return parentBeanFactory.getBean(nameToLookup, requiredType);
			}
		}

		// 添加已创建标记
		if (!typeCheckOnly) {
			markBeanAsCreated(beanName);
		}

		try {
			// 根据名字获取合并过的对应的RootBeanDefinition
			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
			checkMergedBeanDefinition(mbd, beanName, args);

			// 当前Bean依赖的Bean先实例化
			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 + "'");
					}
					registerDependentBean(dep, beanName);
					try {
						getBean(dep);
					}
					catch (NoSuchBeanDefinitionException ex) {
						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
								"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
					}
				}
			}

			// 单例模式对象实例化
			if (mbd.isSingleton()) {
				sharedInstance = getSingleton(beanName, () -> {
					try {
						// 创建单例对象
						return createBean(beanName, mbd, args);
					}
					catch (BeansException ex) {
						destroySingleton(beanName);
						throw ex;
					}
				});
				// 处理FactoryBean情况
				bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
			}

			// proto类型对象创建
			else if (mbd.isPrototype()) {
				// It's a prototype -> create a new instance.
				Object prototypeInstance = null;
				try {
					// 记录当前正在创建的原型对象
					beforePrototypeCreation(beanName);
					// 创建对象
					prototypeInstance = createBean(beanName, mbd, args);
				}
				finally {
					// 移除当前正在创建的原型对象记录
					afterPrototypeCreation(beanName);
				}
				// 处理FactoryBean情况
				bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
			}

			// 其它Scope处理
			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;
		}
	}

	// 检查创建的对象是否是想要的类型,如果不是则尝试进行类型转换
	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()) {
				logger.debug("Failed to convert bean '" + name + "' to required type '" +
						ClassUtils.getQualifiedName(requiredType) + "'", ex);
			}
			throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
		}
	}
	return (T) bean;
}

/**
 * DefaultSingletonBeanRegistry
 */
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
	Assert.notNull(beanName, "Bean name must not be null");
	synchronized (this.singletonObjects) {
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null) {
			// 创建前检查,默认实现是记录当前beanName正在注册中
			beforeSingletonCreation(beanName);
			boolean newSingleton = false;
			boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
			if (recordSuppressedExceptions) {
				this.suppressedExceptions = new LinkedHashSet<>();
			}
			try {
				// 调用前面自定义的内部类实现进行创建
				singletonObject = singletonFactory.getObject();
				newSingleton = true;
			}
			catch (IllegalStateException ex) {
				singletonObject = this.singletonObjects.get(beanName);
				if (singletonObject == null) {
					throw ex;
				}
			}
			catch (BeanCreationException ex) {
				if (recordSuppressedExceptions) {
					for (Exception suppressedException : this.suppressedExceptions) {
						ex.addRelatedCause(suppressedException);
					}
				}
				throw ex;
			}
			finally {
				if (recordSuppressedExceptions) {
					this.suppressedExceptions = null;
				}
				// 创建后置检查,默认实现是移除当前beanName正在注册状态的记录
				afterSingletonCreation(beanName);
			}
			// 将实例化的对象添加到singletonObjects集合,并从earlySingletonObjects中移除
			if (newSingleton) {
				addSingleton(beanName, singletonObject);
			}
		}
		return singletonObject;
	}
}

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

	RootBeanDefinition mbdToUse = mbd;

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

	try {
		// 准备方法覆盖,主要为lookup-method,replace-method等配置准备
		mbdToUse.prepareMethodOverrides();
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
				beanName, "Validation of method overrides failed", ex);
	}

	try {
		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
		// 
		// 一个扩展点,给BeanPostProcessors一个机会去生成一个代理,而不是原来的对象实例
		// 判断spring容器中是否注册了InstantiationAwareBeanPostProcessor
		// 1. 如果有就一次调用postProcessBeforeInstantiation方法(使用第一个该方法返回值不为空的类)
		// 2.然后一次调用所有注册的BeanPostProcessor的postProcessAfterInitialization方法(使用最后一个该方法不为空的类)
		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 {
		// 正真创建Bean的逻辑
		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		if (logger.isDebugEnabled()) {
			logger.debug("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);
	}
}

/**
 * 该方法是单例和原型对象创建公共方法
 * AbstractBeanFactory
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
		throws BeanCreationException {

	// BeanWrapper封装了具体的Bean实例,然后可以很方便地通过调用getPropertyValue和setPropertyValue等方法反射读写Bean的具体属性
	BeanWrapper instanceWrapper = null;
	// 单例模式,先尝试从缓存中取
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		// 调用构造方法创建一个空实例对象,并用beanWrapper进行包装
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	final Object bean = instanceWrapper.getWrappedInstance();
	Class<?> beanType = instanceWrapper.getWrappedClass();
	if (beanType != NullBean.class) {
		mbd.resolvedTargetType = beanType;
	}

	// 一个扩展点
	// 调用所有的后置处理器MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法
	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) {
		// 一个扩展点
		// 提前暴露一个单例工厂方法,确保其它的Bean能引用到此bean
		// 具体内部会遍历后置处理器SmartInstantiationAwareBeanPostProcessor实现类,然后调用getEarlyBeanReference方法
		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
	}

	// 开始对Bean实例进行初始化
	Object exposedObject = bean;
	try {
		// 对bean成员变量进行赋值、 依赖进行注入
		populateBean(beanName, mbd, instanceWrapper);
		// 调用spring内置的各种模板方法
		// 1.BeanNameAware,BeanClassLoaderAware,BeanFactoryAware
		// 2.遍历BeanPostProcessor.postProcessBeforeInitialization方法
		// 3.调用InitializingBean.afterPropertiesSet方法
		// 4.调用init方法
		// 5.遍历BeanPostProcessor.postProcessAfterInitialization方法
		exposedObject = initializeBean(beanName, exposedObject, mbd);
	}
	catch (Throwable ex) {
		if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
			throw (BeanCreationException) ex;
		}
		else {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
		}
	}

	......
	// 如果实现了Disposable接口,会在这里进行注册,最后在销毁的时候调用相应的destroy方法
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanCreationException(
				mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
	}

	return exposedObject;
}

虽然有很多细节没有展开讲,因为在一篇讲会比较多,后面会一一展开说,到这里,就说完了spring容器中BeanDefinition对象实例化的过程,再结合上一篇,从配置类到实例化整个过程就讲完了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值