Spring源码分析(一)IoC容器

Spring Framework,也就是我们常说的Spring框架,我觉得其中最核心的部分应该就是IOC容器了,Spring的IOC容器的实现也叫做DI,也就是依赖注入。这篇博客要说的就是这其中的大概的实现过程。

AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);

Spring的启动只需要这样一行代码就可以了

	public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
		this();
		register(componentClasses);
		refresh();
	}

先看一看类图

在这个类图中,最核心的一个就是AbstractApplicationContext。

接着看代码,首先初始化注解以及XML的读取或者扫描的两个类,接着将实例化AnnotationConfigApplicationContext时传入的类,也就是register方法中传入的类,生成该类的BeanDefinition(这里必须先要弄明白BeanDefinition和Bean的区别,而且注意生成的仅仅是这个register类的BeanDefinition),存入beanDefinitionMap,而此时并没有执行扫描,接着执行refresh方法。

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			// context refresh开始之前的操作
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			// 获取一个BeanFactory ,通常是 DefaultListableBeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// beanFactory的一些预操作
			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// 允许这里对BeanFactory做一些处理,默认空实现
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// 执行BeanFactory的后置处理器
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// 注册所有的BeanPostProcessor到beanFactory中
				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// 国际化
				// Initialize message source for this context.
				initMessageSource();

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

				//初始化一些特殊的bean ,交给子类实现,默认空实现
				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// 注册ApplicationListener到事件传播器中(实际上只是放入了名称)
				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//实例化非懒加载的bean
				finishBeanFactoryInitialization(beanFactory);

				//spring容器构建结束
				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				//清除缓存
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

首先是prepareRefresh方法,这里主要是web环境下加载一些配置属性,不过这需要子类GenericWebApplicationContext去实现,如果是当前AnnotationConfigApplicationContext ,默认无动作

	protected void prepareRefresh() {
		// Switch to active.
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);
		this.active.set(true);

		if (logger.isDebugEnabled()) {
			if (logger.isTraceEnabled()) {
				logger.trace("Refreshing " + this);
			}
			else {
				logger.debug("Refreshing " + getDisplayName());
			}
		}

		// Initialize any placeholder property sources in the context environment.
		// web环境下加载一些配置属性
		initPropertySources();

		//验证配置属性
		// Validate that all properties marked as required are resolvable:
		// see ConfigurablePropertyResolver#setRequiredProperties
		getEnvironment().validateRequiredProperties();

		// Store pre-refresh ApplicationListeners...
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
			// Reset local application listeners to pre-refresh state.
			this.applicationListeners.clear();
			this.applicationListeners.addAll(this.earlyApplicationListeners);
		}

		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}

接着获取一个BeanFactory,看一看BeanFactory的类图

接着prepareBeanFactory方法,准备工厂,就是对工厂注册了一些需要的后置处理器以及环境等等

接着postProcessBeanFactory方法,允许这里对BeanFactory做一些处理,默认空实现

接着invokeBeanFactoryPostProcessors方法,执行BeanFactory的后置处理器

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

这个方法比较长,整体来说分为两个部分。

前一部分是执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法。

后一部分是执行BeanFactoryPostProcessor的postProcessBeanFactory方法。

 

首先先说前一部分,也就是执行postProcessBeanDefinitionRegistry的这部分

先是从当前BeanFactoryPostProcessor列表中找出BeanDefinitionRegistryPostProcessor类型的,并执行,

接着从BeanFactory中获取,先对继承了PriorityOrdered接口的排序并执行,

再对继承了Ordered接口的排序并执行,

最后对剩下的依次执行。

 

再说后一部分,也就是执行postProcessBeanFactory的这部分

同样是先对继承了PriorityOrdered接口的排序并执行,

再对继承了Ordered接口的排序并执行,

最后对剩下的依次执行。

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		Set<String> processedBeans = new HashSet<>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			//找出BeanFactoryPostProcessor列表中的BeanDefinitionRegistryPostProcessor对beanFactory轮流处理
			//其他的BeanFactoryPostProcessor放入regularPostProcessors集合最后调用
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}


			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			//先找出实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor
			//执行postProcessBeanDefinitionRegistry,并且放入registryProcessors集合
			//同时放入processedBeans表示已经执行过了
			//重点关注 ConfigurationClassPostProcessor,用于扫描生成BeanDefinition
			ConfigurationClassPostProcessor to;

			//接着找出实现了Ordered的BeanDefinitionRegistryPostProcessor
			//执行postProcessBeanDefinitionRegistry,并且放入registryProcessors集合
			//同时放入processedBeans表示已经执行过了


			//最后找出不在processedBeans中的BeanDefinitionRegistryPostProcessor
			//执行postProcessBeanDefinitionRegistry,并且放入registryProcessors集合

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}

			//最后执行registryProcessors集合中所有成员的postProcessBeanFactory方法
			//以及regularPostProcessors中的所有成员的postProcessBeanFactory
			// 需要重点关注 ConfigurationClassPostProcessor
			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		//找出BeanFactoryPostProcessor
		//按照之前的逻辑再来一次
		//需要关注的是EventListenerMethodProcessor 用于生成注解的ApplicationListener
		EventListenerMethodProcessor to;
		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}

在执行postProcessBeanDefinitionRegistry的过程中,有一个最为重要的bean是ConfigurationClassPostProcessor,这个后置处理器会进行扫描,将所有的扫描路径下的类生成一个BeanDefinition列表,为接下来的生成Bean做准备

 

接着registerBeanPostProcessors(beanFactory)方法,这里将所有的BeanPostProcessor找出来并注册到了容器中。

PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);

其中的方法和上面的BeanFactoryPostProcessor的那部分逻辑基本类似。

再接着执行initMessageSource方法,,这个主要用来处理国际化的

再接着是initApplicationEventMulticaster方法,注册一个事件传播器,

再接着是onRefresh方法,默认空实现。

再往下看registerListeners方法,注册监听器到容器中。

for (ApplicationListener<?> listener : getApplicationListeners()) {
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

再接着看finishBeanFactoryInitialization方法。这里就是真正的bean的生命周期开始执行了。

会去调用preInstantiateSingletons方法。

	// Trigger initialization of all non-lazy singleton beans...
		// 循环beanNames,实例化单例bean
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);

			//判断 非抽象的,单例的,非懒加载的
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {

				//判断是不是FactoryBean
				if (isFactoryBean(beanName)) {
					//FactoryBean 需要带上&前缀才能找到真正的bean
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					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(beanName);
						}
					}
				}
				else {
					//加载bean
					getBean(beanName);
				}
			}
		}

getBean(beanName)方法就是开始去加载生成bean了。

接着是doGetBean方法

首先会调用getSingleton方法,第一次进来肯定是什么也获取不到的。

	@Nullable
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {

		//先从一级缓存singletonObjects中获取 singletonObjects同样也是最终实例的存储容器
		Object singletonObject = this.singletonObjects.get(beanName);
		//如果singletonObjects获取不到,并且正在创建中
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			//加锁,确保原子性
			synchronized (this.singletonObjects) {
				//再从二级缓存earlySingletonObjects中获取
				singletonObject = this.earlySingletonObjects.get(beanName);
				//如果二级缓存是空的,并且支持循环依赖
				if (singletonObject == null && allowEarlyReference) {
					//从三级缓存singletonFactories中获取
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						//singletonFactories中存放的是lambda对象,通过getObject生成二级缓存,并且放入二级缓存中去
						singletonObject = singletonFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return singletonObject;
	}

接着还会尝试从parent父容器中获取

//从parent容器中查看能不能获取到
			// Check if bean definition exists in this factory.
			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 if (requiredType != null) {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
				else {
					return (T) parentBeanFactory.getBean(nameToLookup);
				}
			}

再往下,获取depenceOn,先加载依赖项

// Guarantee initialization of beans that the current bean depends on.
				//判断是不是有dependsOn的bean ,有的话,先去生成dependsOn的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);
						}
					}
				}

最后根据不同的scope创建bean

//创建bean ,不同的scope有不同的创建方式
				// Create bean instance.
				//创建单例
				if (mbd.isSingleton()) {
					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.
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
                //创建原型
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						//将bean移除正在创建的集合标签中
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}
				//其他scope
				else {
					String scopeName = mbd.getScope();
					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 ScopeNotActiveException(beanName, scopeName, ex);
					}
				}
			}

主要看单例的创建过程。也就是createBean(beanName, mbd, args)方法。

首先执行后置处理器的postProcessorBeforeInstantiation方法,尝试返回自定义的代理对象(和aop无关)

// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			 // 给予后置处理器们一个机会,返回自己的代理对象
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			 //先调用postProcessBeforeInstantiation
			//如果有自己代理对象返回,那就直接调用postProcessAfterInitialization
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}

再接着调用doCreateBean方法

Object beanInstance = doCreateBean(beanName, mbdToUse, args);

首先会实例化对象

//实例化,创建对象
if (instanceWrapper == null) {
	//通过构造方法实例化对象
	instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//bean实例
Object bean = instanceWrapper.getWrappedInstance();

实例生成是通过构造器反射生成的,构造器的注入也是在这里进行

	//构造器注入
		// 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);
		}

接着调用applyMergedBeanDefinitionPostProcessors方法,执行BeanFactory中所有实现了MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法。

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

再接着添加三级缓存,三级缓存是为了延迟执行,就是说如果确实有循环依赖,才会在后续循环依赖的地方执行该方法,否则不会执行该方法。

// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//判断是否允许循环依赖,并且正在创建中
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			//添加三级缓存
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

再往下,执行populateBean方法,填充Bean实例的属性。

首先执行postProcessAfterInstantiation方法

	// 调用postProcessAfterInstantiation 实例化完成后的回调方法
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
				if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					return;
				}
			}
		}

接下来执行postProcessProperties方法,用后置处理器的模式进行属性的填充

//执行填充属性的后置处理器
		//重点注意CommonAnnotationBeanPostProcessor和 AutowiredAnnotationBeanPostProcessor
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
				PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
				if (pvsToUse == null) {
					if (filteredPds == null) {
						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
					}
					pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						return;
					}
				}
				pvs = pvsToUse;
			}
		}

这里面最重要的是CommonAnnotationBeanPostProcessor和AutowiredAnnotationBeanPostProcessor,分别是对@Resource和@Autowired注解的属性进行注入

接下来调用initializeBean方法。

首先调用invokeAwareMethods方法,方法中调用了三个Aware的方法,BeanNameAware,BeanClassLoaderAware和BeanFactoryAware

	private void invokeAwareMethods(final String beanName, final Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof BeanNameAware) {
				((BeanNameAware) bean).setBeanName(beanName);
			}
			if (bean instanceof BeanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			if (bean instanceof BeanFactoryAware) {
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}

接着调用applyBeanPostProcessorsBeforeInitialization,方法里获取了所有BeanPostProcessor调用postProcessBeforeInitialization方法。

	@Override
	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessBeforeInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

其中有几个比较重要的后置处理器。

首先是ApplicationContextAwareProcessor,如果当前bean实现了几个Aware接口,会调用invokeAwareInterfaces方法

private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof EnvironmentAware) {
			((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
		}
		if (bean instanceof EmbeddedValueResolverAware) {
			((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
		}
		if (bean instanceof ResourceLoaderAware) {
			((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
		}
		if (bean instanceof ApplicationEventPublisherAware) {
			((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
		}
		if (bean instanceof MessageSourceAware) {
			((MessageSourceAware) bean).setMessageSource(this.applicationContext);
		}
		if (bean instanceof ApplicationContextAware) {
			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
		}
	}

接着是InitDestroyAnnotationBeanPostProcessor,方法中就是执行注解了@PostConstruct的初始化方法

所有的BeanPostProcessor执行完之后,再往下调用invokeInitMethods方法,如果当前bean实现了InitializingBean,会调用afterPropertiesSet的初始化方法。

((InitializingBean) bean).afterPropertiesSet()

再往下调用自定义的初始化方法,就是xml中配置的那个

	if (mbd != null && bean.getClass() != NullBean.class) {
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}

再往下调用applyBeanPostProcessorsAfterInitialization方法,方法中同样是取出所有的BeanPostProcesser,不同的是这里调用postProcessAfterInitialization方法

	@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

其中重要的是AbstractAutoProxyCreator,这里进行了Aop代理

还有一个是ApplicationListenerDetector,这个后置处理器中判断了当前Bean有没有实现ApplicationListener,有的话添加进applicationListeners中

@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (bean instanceof ApplicationListener) {
			// potentially not detected as a listener by getBeanNamesForType retrieval
			Boolean flag = this.singletonNames.get(beanName);
			if (Boolean.TRUE.equals(flag)) {
				// singleton bean (top-level or inner): register on the fly
				this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
			}
			else if (Boolean.FALSE.equals(flag)) {
				if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
					// inner bean with other scope - can't reliably process events
					logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
							"but is not reachable for event multicasting by its containing ApplicationContext " +
							"because it does not have singleton scope. Only top-level listener beans are allowed " +
							"to be of non-singleton scope.");
				}
				this.singletonNames.remove(beanName);
			}
		}
		return bean;
	}

至此,bean就创建完成了,最后将bean放入singletonObjects中,也就是容器中。

if (newSingleton) {
		addSingleton(beanName, singletonObject);
	}
	/**
	 * Add the given singleton object to the singleton cache of this factory.
	 * <p>To be called for eager registration of singletons.
	 * @param beanName the name of the bean
	 * @param singletonObject the singleton object
	 */
	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);
		}
	}

bean创建完成。

当所有的bean创建完成以后,会依次调用实现了SmartInitializingSingleton的后置方法

//触发SmartInitializingSingleton的回调方法 afterSingletonsInstantiated
//重点注意 EventListenerMethodProcessor
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
	Object singletonInstance = getSingleton(beanName);
	if (singletonInstance instanceof SmartInitializingSingleton) {
		SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				smartSingleton.afterSingletonsInstantiated();
				return null;
			}, getAccessControlContext());
		}
		else {
			smartSingleton.afterSingletonsInstantiated();
		}
	}

执行完之后,finishBeanFactoryInitialization方法也就执行完成了

再接着是finishRefresh方法

	protected void finishRefresh() {
		// Clear context-level resource caches (such as ASM metadata from scanning).
		clearResourceCaches();

		//向context中注册一个LifecycleProcessor
		// Initialize lifecycle processor for this context.
		initLifecycleProcessor();

		//执行实现了Lifecycle的start方法
		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

		//发布一个ContextRefreshedEvent事件
		// Publish the final event.
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		LiveBeansView.registerApplicationContext(this);
	}

首先是initLifecycleProcessor方法,注册了一个LifecycleProcessor

/**
	 * Initialize the LifecycleProcessor.
	 * Uses DefaultLifecycleProcessor if none defined in the context.
	 * @see org.springframework.context.support.DefaultLifecycleProcessor
	 */
	protected void initLifecycleProcessor() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
			this.lifecycleProcessor =
					beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
			if (logger.isTraceEnabled()) {
				logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
			}
		}
		else {
			DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
			defaultProcessor.setBeanFactory(beanFactory);
			this.lifecycleProcessor = defaultProcessor;
			beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
			if (logger.isTraceEnabled()) {
				logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
						"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
			}
		}
	}

注册好之后调用onRefresh方法,方法中调用startBeans

@Override
	public void onRefresh() {
		startBeans(true);
		this.running = true;
	}

方法中首先获取容器中所有实现了Lifecycle的bean,接着做了个判断,如果实现了SmartLifecycle,那么isAutoStartup返回true的进入,或者autoStartupOnly是false,不过当前传入的是true,进入后,获取所有Lifecycle的phase,根据phase的大小排序,小的先执行start方法,大的后执行

private void startBeans(boolean autoStartupOnly) {
		//获取所有实现了Lifecycle的bean
		Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
		Map<Integer, LifecycleGroup> phases = new HashMap<>();
		//找出需要调用start方法的Lifecycle
		//一个是autoStartupOnly设置了false,或者是实现了SmartLifecycle并且isAutoStartup属性是true
		//通过getPhase获取到的值排序,依次执行start方法
		lifecycleBeans.forEach((beanName, bean) -> {
			if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
				int phase = getPhase(bean);
				LifecycleGroup group = phases.get(phase);
				if (group == null) {
					group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
					phases.put(phase, group);
				}
				group.add(beanName, bean);
			}
		});
		if (!phases.isEmpty()) {
			List<Integer> keys = new ArrayList<>(phases.keySet());
			Collections.sort(keys);
			for (Integer key : keys) {
				phases.get(key).start();
			}
		}
	}

返回,接着调用publishEvent方法。创建并发布ContextRefreshedEvent事件

getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);

最后调用resetCommonCaches清除各种缓存,spring框架启动就到此结束了。

当然spring框架中肯定还有许多的细节,因为spring框架是真的非常难,非常庞大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值