Spring中IOC容器的整体创建过程(源码解析)

Spring中IOC容器的整体创建过程(源码解析)

  • 内容
  • 一、Spring创建IOC容器源码解析配置
  • 二、IOC容器创建整体流程
  • 三、IOC容器创建流程分步解
    • 由于此处源码过多,只给出大体过程,不会都贴上源码,有需要的可以自行进行debug作为参照
  • 总结


内容

记录下Spring中IOC创建的整体流程

一、Spring创建IOC容器源码解析配置

1.要了解Spring的源码运行流程,先从总体框架入手,并且加上debug调试完成 2.定义一个配置文件类,再加上一个测试类,然后debug启动,所有开发都在idea中完成
配置文件类
@Configuration
@EnableAspectJAutoProxy
public class SpringAopConfig
{
    @Bean
    public MathCalculator mathCalculator()
    {
        return new MathCalculator();
    }

    @Bean
    public LogAspects logAspects()
    {
        return new LogAspects();
    }
}
测试类
    @Test
    public void aopTest01()
    {
 		//断点可加在这一行,然后进行debug运行
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringAopConfig.class);
        MathCalculator bean = applicationContext.getBean(MathCalculator.class);
        System.out.println(bean.div(1, 2));
    }

二、IOC容器创建整体流程

进入调试后得到以下代码,重点关注 refresh() 方法

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

跳进**refresh()**方法,发现整个IOC容器的整体流程如下:

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			//1.刷新前的预处理
			prepareRefresh()
			//2.获取BeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
			//3.BeanFactory的预准备工作(即设置BeanFactory的一些属性)
			prepareBeanFactory(beanFactory)
			try {
				//4.BeanFactory准备工作完成后进行的后置处理操作
				postProcessBeanFactory(beanFactory)
				
============以上都是关于BeanFactory的创建及预准备工作==============

				//5.执行BeanFactoryPostProcessors(即后置处理器)
				invokeBeanFactoryPostProcessors(beanFactory)
				//6.注册BeanPostProcessors
			    //注:此处是bean的后置处理器,上面是BeanFactory的后置处理器
				registerBeanPostProcessors(beanFactory)
				//7.初始化MessageSource组件(用于国际化功能、消息绑定、消息解析等)
				initMessageSource()
				//8.初始化事件派发器
				initApplicationEventMulticaster()
				//9.用于子类重写该方法,可以在容器刷新的时候自定义逻辑
				onRefresh()
				//10.注册所有的ApplicationListener组件
				registerListeners()
				//11.最重要的一步:初始化所有剩下的单实例bean
				finishBeanFactoryInitialization(beanFactory)
				//12.完成BeanFactory的初始化创建工作,至此IOC容器创建完成
				finishRefresh();
			}

上面分析了IOC容器创建的整体流程,接下来对每一步进行详细的解析


三、IOC容器创建流程分步解

由于此处源码过多,只给出大体过程,不会都贴上源码,有需要的可以自行进行debug作为参照


1.prepareRefresh()

刷新前的预处理

	@Override
	protected void prepareRefresh() {
		this.scanner.clearCache();
		super.prepareRefresh();
	}

此步主要完成以下功能:

  1. initPropertySources()
    初始化一些属性设置,用于子类自定义个性化的属性设置
  2. getEnvironment().validateRequiredProperties();
    检验自定义属性的合法性
  3. this.earlyApplicationEvents = new LinkedHashSet();
    保存IOC容器中的一些早期的事件

2.obtainFreshBeanFactory()

获取BeanFactory

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}
此步主要完成以下功能:
  1. refreshBeanFactory();
    创建了一个默认的BeanFactory并设置了一个序列化ID,然后将其保存至IOC容器中,由于后续获取
  2. getBeanFactory();
    获取刚刚创建的BeanFactory对象
  3. return beanFactory;
    将刚刚获取的BeanFactory对象返回

3.prepareBeanFactory(beanFactory)

BeanFactory的预准备工作

	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

		// BeanFactory interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// Register early post-processor for detecting inner beans as ApplicationListeners.
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			// Set a temporary ClassLoader for type matching.
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}

		// Register default environment beans.
		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
		}
		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
		}
		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
		}
	}

此步主要完成以下功能:

  1. 设置BeanFactory的类加载器,支持表达式解析器等…
  2. 添加部分BeanPostProcessor
  3. 设置忽略的自动装配的接口,例如EnvironmentAware、EmbeddedValueResolverAware、xxx等
  4. 注册可以解析的自动装配组件,从而我们可以直接在任何组件中注入这些自动装配组件(BeanFactory、ApplicationContext、xxx等)
  5. 添加编译时的AspectJ
  6. 给BeanFactory中注册一些能用的组件
    environment【StandardEnvironment】
    systemProperties【Map】等

4.postProcessBeanFactory(beanFactory)

BeanFactory准备工作完成后进行的后置处理工作(留给子类进行重写)

以上4步都是关于BeanFactory的创建、准备、初始化工作


5.**invokeBeanFactoryPostProcessors(beanFactory)**

执行BeanFactoryPostProcessor,即BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的

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

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

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

			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<BeanDefinitionRegistryPostProcessor>();

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

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

		// 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<BeanFactoryPostProcessor>();
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
		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<BeanFactoryPostProcessor>();
		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<BeanFactoryPostProcessor>();
		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();
	}

此处有两个接口BeanFactoryPostProcessor和 BeanDefinitionRegistryPostProcessor,两个接口的方法依次执行

  • 先执行BeanDefinitionRegistryPostProcessor的方法
  • 1)获取所有的BeanDefinitionRegistryPostProcessor
  • 2)先执行实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor中的方法,调用BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry(registry);
  • 3)再执行实现了Ordered接口的BeanDefinitionRegistryPostProcessor中的方法
  • 4)最后执行没有实现任何优先级或是顺序接口的BeanDefinitionRegistryPostProcessor中的方法
  • 再执行BeanFactoryPostProcessor的方法
  • 1)其执行顺序如上一样,都是先查找优先级高的BeanFactoryPostProcessor,然后依次执行

6.registerBeanPostProcessors(beanFactory)
注册BeanPostProcessor(Bean的后置处理器,上面的是BeanFactory的后置处理器),此处只是注册,还未执行
并且对于不同接口的BeanPostProcessor,其在Bean前后的执行时机也是不一样的,主要有如下BeanPostProcessor

  • BeanPostProcessor
  • MergedBeanDefinitionPostProcessor
  • InstantiationAwareBeanPostProcessor
  • SmartInstantiationAwareBeanPostProcessor
  • DestructionAwareBeanPostProcess

注册代码如下:

public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

该部分主要流程如下:

1). 获取所有的BeanPostProcessor
2).先注册实现了PriortyOrdered接口的BeanPostProcessor,调用registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors)完成注册
3).再注册实现了Ordered接口的BeanPostProcesso
4).注册没有实现任何顺序接口的的BeanPostProcesso	
5).最后注册MergedBeanDefinitionPostProcessor

7.initMessageSource()
初始化MessageResource组件(用于做国际化功能、消息绑定、消息解析等)


8.initApplicationEventMulticaster()
初始化事件派发器

代码如下:

	protected void initApplicationEventMulticaster() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
						APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
						"': using default [" + this.applicationEventMulticaster + "]");
			}
		}
	}

主要有以下步骤:

1). 从IOC容器中获取BeanFactory
2). 查找BeanFactory中是否有派发器ApplicationEventMulticaster,如果有则返回,如果没有进行下一步
3). 在BeanFactory中没有派发器,那么创建一个默认的派发器SimpleApplicationEventMulticaster
4). 并将这个创建的派发器注册到BeanFactory中,从而以后其它组件可以自动注入派发器

9.onRefresh()
留给子类重写该方法,用于在容器刷新时自定义逻辑


10.registerListeners()
注册监听器,将项目中所有的ApplicationListener注入到BeanFactory的派发器中

protected void registerListeners() {
		// Register statically specified listeners first.
		for (ApplicationListener<?> listener : getApplicationListeners()) {
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let post-processors apply to them!
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		// Publish early application events now that we finally have a multicaster...
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (earlyEventsToProcess != null) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

主要有以下步骤:

1). 从IOC容器中拿到所有的ApplicationListener
2).将所有的ApplicationListener注入到ApplicationEventMulticaste,这样就可以完成事件驱动
3).利用派发器派发之前步骤产生的事件

11.finishBeanFactoryInitialization(beanFactory)
整个IOC容器创建中最重要的一步,初始化所有剩下的单实例bean

public void preInstantiateSingletons() throws BeansException {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("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.
		List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
					boolean isEagerInit;
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
							@Override
							public Boolean run() {
								return ((SmartFactoryBean<?>) factory).isEagerInit();
							}
						}, getAccessControlContext());
					}
					else {
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					if (isEagerInit) {
						getBean(beanName);
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged(new PrivilegedAction<Object>() {
						@Override
						public Object run() {
							smartSingleton.afterSingletonsInstantiated();
							return null;
						}
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

主要有以下步骤:

1). 获取容器中的所有bean,利用for循环依次进行初始化和创建对象,for循环中流程如下:
1.1). 先获取单个bean的定义信息RootBeanDefinition
1.2). 判断其是否抽象类、是否单实例的、是否懒加载
1.2.1). 如果满足上述条件,再判断是否为FactoryBean(如果是,则调用FactoryBean接口的getObject方法创建bean)
1.2.2). 如果不是FactoryBean,则调用getBean(beanName)创建bean

getBean方法的代码如下:

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

		final String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// 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 (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 {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				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);
						getBean(dep);
					}
				}

				// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						@Override
						public Object getObject() throws BeansException {
							try {
								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 {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				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, new ObjectFactory<Object>() {
							@Override
							public Object getObject() throws BeansException {
								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;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
			try {
				return getTypeConverter().convertIfNecessary(bean, requiredType);
			}
			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;
	}

对于getBean方法中代码解释如下:

  • 先从缓存中获取保存的单实例bean,如果能够获取到就说明该bean之前已被创建
  • 如果缓存中获取不到,那么就开始创建bean,其流程如下
    • 标记当前bean已被创建
    • 获取bean的定义信息 RootBeanDefinition
    • 获取当前bean依赖的其它bean
    • 调用createBean(beanName, mbd, args)完成bean的创建
    • Object bean = resolveBeforeInstantiation(beanName, mbdToUse),让InstantiationAwareBeanPostProcessor类型的BeanPostProcessor执行,即执行一种类型的后置处理器,先执行postProcessBeforeInstantiation,如果该方法返回了一个bean,那么再执行applyBeanPostProcessorsAfterInitialization方法
    • 如果该方法没有返回一个bean,采用doCreateBean(beanName, mbdToUse, args)方法生成一个bean实例,对于doCreateBean()方法流程如下:
      • 首先利用反射创建该bean
      • 然后bean创建后,让MergedBeanDefinitionPostProcessor的BeanPostProcessor执行,执行其postProcessMergedBeanDefinition方法
      • 然后再调用populateBean()方法为bean的属性赋值,在属性赋值之前会让InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation、postProcessPropertyValues方法执行,然后再调用applyPropertyValues为bean的属性赋值
      • 属性赋值后,调用initializeBean()对bean进行初始化
        • invokeAwareMethods(beanName, bean);执行xxxAware接口的方法,从而可以使用户实现ioc容器内部组件的获取
        • 执行BeanPostProcessor的postProcessBeforeInitialization方法
        • 初始化bean
        • 执行BeanPostProcessor的postProcessAfterInitialization方法
      • 注册bean的销毁方法
      • 将创建的bean加入到IOC容器中
      • 注:ioc容器其实就是一些Map集合,这些集合保存了单实例Bean,环境信息等因素
2). 获取容器中的所有bean,利用for循环依次判断其是否为SmartInitializingSingleton类型,如果是则调用afterSingletonsInstantiated方法

11.finishRefresh()
完成BeanFactory的初始化创建工作,IOC容器就创建完成

	protected void finishRefresh() {
		// Initialize lifecycle processor for this context.
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		publishEvent(new ContextRefreshedEvent(this));

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

该步主要完成以下工作:

  • initLifecycleProcessor():初始化和生命周期有关的后置处理器,并将其加入IOC容器
  • 拿到之前加入的生命周期后置处理器,并回调其onRefresh()方法
  • publishEvent(new ContextRefreshedEvent(this));发布容器刷新完成事件

总结

1) Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息,无论是采用xml注册Bean还是使用注解(@Bean、@Service...) 2) Spring会在合适的时机获取这些Bean的信息并进行创建,创建完成后加入容器以便后续调用
2.1)第一个时机:用到这个bean的时候,会调用getBean()创建,然后保存
2.2)第二个时机:统一创建所有剩下的单实例Bean,即finishBeanFactoryInitialization(beanFactory
3) 需要掌握后置处理器(BeanPostProcessor)的执行时机
每一个Bean创建完成,都会使用各种后置处理器进行处理,从而增强Bean
例如AutowiredAnnotationBeanPostProcessor,用于处理自动注入
例如AnnotationAwareAspectJAutoProxyCreator,用于AOP
4)需要掌握事件驱动模型,即ApplicationListener

你可能感兴趣的:(java,ioc,源码,spring,设计模式)