目录

创建Spring容器:

1、prepareRefresh()预处理刷新

2、obtainFreshBeanFactory()  创建并获取BeanFactory

refreshBeanFactory():

3、prepareBeanFactory(beanFactory):BeanFactory进行一些设置

4、postProcessBeanFactory(beanFactory);BeanFactory准备工作完成后进行的后置处理工作;

5、invokeBeanFactoryPostProcessors(beanFactory);执行BeanFactory后置处理器的方法;

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

6、registerBeanPostProcessors(beanFactory);注册BeanPostProcessor

7、initMessageSource();初始化MessageSource组件(做国际化功能;消息绑定,消息解析)

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

9、onRefresh();留给子类,重写该方法,自定义逻辑。

10、registerListeners();将所有的ApplicationListener注册进容器;

11、finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean;

12、finishRefresh();完成BeanFactory的初始化创建工作;IOC容器就创建完成;

initLifecycleProcessor:

getLifecycleProcessor().onRefresh():

总结:


创建Spring容器:

	@Test
	public void test01(){
		AnnotationConfigApplicationContext applicationContext  = new AnnotationConfigApplicationContext(SpringConfig.class);
		
		applicationContext.close();
	}

这是我们在做单元测试时常用的Spring容器的创建和关闭的代码。Spring容器创建完成后,我们所需要的bean都会被注册进容器中。但是Spring是如何把我们需要的bean创建出来,以及创建出bean后存放到哪里供我们调用的呢?

new AnnotationConfigApplicationContext(Config.class)的源代码:

	public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		this(); //调用无参构造,创建容器对象
		register(annotatedClasses);//注册配置文件信息
		refresh(); //Spring容器的核心操作,刷新容器,创建bean
	}

创建Spring容器对象时,会调用refresh方法,该方法中包含了Spring的所有操作流程,是Spring容器的核心方法:

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {			
			prepareRefresh();//预处理刷新
			// 获取BeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
			
			prepareBeanFactory(beanFactory); // BeanFactory的一些设置
			try {
				//BeanFactory准备工作完成后进行的后置处理工作;
				postProcessBeanFactory(beanFactory); 

				// 执行BeanFactoryPostProcessor后置处理器中的方法
				invokeBeanFactoryPostProcessors(beanFactory);

				// 注册BeanPostProcessor用于拦截bean的创建
				registerBeanPostProcessors(beanFactory);

				// 初始化MessageSource组件(做国际化功能;消息绑定,消息解析);
				initMessageSource();

				// 初始化事件派发器;
				initApplicationEventMulticaster();

				// 子类重写这个方法,在容器刷新的时候可以自定义逻辑;
				onRefresh();

				// 注册容器中所有的ApplicationListener;
				registerListeners();

				//初始化所有剩下的单实例bean
				finishBeanFactoryInitialization(beanFactory);

				// 完成BeanFactory的初始化创建工作;IOC容器就创建完成
				finishRefresh();
			}catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}
				destroyBeans(); //销毁已创建的bean
				cancelRefresh(ex);//取消容器刷新操作
				throw ex;
			}finally { 
				resetCommonCaches(); //重置Spring核心中的公共内省缓存
			}
		}
	}

从refresh的源码中可以看出,容器创建完成一共分为12个步骤,下面就来看看每一步中容器都做了什么:

1、prepareRefresh()预处理刷新

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

		if (logger.isInfoEnabled()) {
			logger.info("Refreshing " + this);
		}

		// 初始化一些属性设置;空方法,子类重写,自定义个性化的属性设置方法;
		initPropertySources();

		//检验自定义属性的合法等
		getEnvironment().validateRequiredProperties();

		// 保存容器中的一些早期的事件;
		this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
	}

2、obtainFreshBeanFactory()  创建并获取BeanFactory

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory(); //刷新beanFactory,创建一个beanFactory
		ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //返回上一步创建好的beanFactory
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}

refreshBeanFactory():

	@Override
	protected final void refreshBeanFactory() throws IllegalStateException {
		if (!this.refreshed.compareAndSet(false, true)) {
			throw new IllegalStateException(
					"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
		}
		this.beanFactory.setSerializationId(getId()); //设置beanFactory的ID
	}

this.beanFactory:

    private final DefaultListableBeanFactory beanFactory;

	public GenericApplicationContext() {
		this.beanFactory = new DefaultListableBeanFactory();
	}

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【ApplicationContextAwareProcessor】
  •     3)、设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
  •     4)、注册可以解析的自动装配;我们能直接在任何组件中自动注入: BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
  •     5)、添加BeanPostProcessor【ApplicationListenerDetector】
  •     6)、添加编译时的AspectJ;
  •     7)、给BeanFactory中注册一些能用的组件;environment<ConfigurableEnvironment>、systemProperties<Map<String, Object>>、  systemEnvironment<Map<String, Object>>,可以从容器中直接获取。

4、postProcessBeanFactory(beanFactory);BeanFactory准备工作完成后进行的后置处理工作;

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	}

postProcessBeanFactory是一个空方法,子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置。

   ============================到这里beanFactory的预准备工作创建完成======================

5、invokeBeanFactoryPostProcessors(beanFactory);执行BeanFactory后置处理器的方法;

	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            //执行BeanFactoryPostProcessor
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

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

		//先调用BeanDefinitionRegistryPostProcessors 
		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);
				}
			} 

			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();

			// 先调用实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessors 
			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();

			//再调用实现Ordered接口的BeanDefinitionRegistryPostProcessors 
			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();

			// 最后调用其他beandefinitionregistrypostprocessor,直到不再出现其他bean为止。
			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();
			}

			// 现在,调用到目前为止处理的所有处理器的postProcessBeanFactory回调。
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			//注册的工厂处理器
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		} 
            //开始调用BeanFactoryPostProcessor,类似于调用BeanDefinitionRegistryPostProcessors 
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

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

invokeBeanFactoryPostProcessors方法主要作用是执行BeanFactoryPostProcessor。BeanFactoryPostProcessor是BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的;

BeanFactoryPostProcessor有一个子接口BeanDefinitionRegistryPostProcessor,他们的执行顺序和执行的时机不同。

  • BeanFactoryPostProcessor的作用是:在BeanFactory标准初始化之后调用,来定制和修改BeanFactory的内容;执行时机是:所有的bean定义已经保存加载到beanFactory,但是bean的实例还未创建
  • BeanDefinitionRegistryPostProcessor的作用是:给容器中再额外添加一些组件,执行时机是:在所有bean定义信息将要被加载,bean实例还未创建的;

BeanFactoryPostProcessor是在bean定义信息加载完成,但bean实例还未创建时执行,而BeanDefinitionRegistryPostProcessor是在bean定义信息将要被加载,但bean实例还未被创建时执行,因此BeanDefinitionRegistryPostProcessor是优先于BeanFactoryPostProcessor执行的。

了解了这些,再来看看上面这段长长的源代码,其实所做的事情很简单:

  •  先执行BeanDefinitionRegistryPostProcessor

        1)、获取所有的BeanDefinitionRegistryPostProcessor;
        2)、先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor、
            postProcessor.postProcessBeanDefinitionRegistry(registry)
        3)、再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
            postProcessor.postProcessBeanDefinitionRegistry(registry)
        4)、最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
            postProcessor.postProcessBeanDefinitionRegistry(registry)

  •             再执行BeanFactoryPostProcessor的方法

        1)、获取所有的BeanFactoryPostProcessor
        2)、先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、
            postProcessor.postProcessBeanFactory()
        3)、在执行实现了Ordered顺序接口的BeanFactoryPostProcessor;
            postProcessor.postProcessBeanFactory()
        4)、最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor;
            postProcessor.postProcessBeanFactory()

6、registerBeanPostProcessors(beanFactory);注册BeanPostProcessor

注册BeanPostProcessor,为IOC容器创建bean做准备。详情可参考博客:Spring IOC源码解析_三水写代码的博客-CSDN博客

7、initMessageSource();初始化MessageSource组件(做国际化功能;消息绑定,消息解析)

	protected void initMessageSource() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory(); 
            //看容器中是否有ID为MESSAGE_SOURCE_BEAN_NAME的组件
		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
			this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); //赋值给messageSource
			// 让MessageSource知道父消息源。
			if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
				HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
				if (hms.getParentMessageSource() == null) {
					//如果没有已注册的父消息源,则只将父上下文设置为父消息源
					hms.setParentMessageSource(getInternalParentMessageSource());
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Using MessageSource [" + this.messageSource + "]");
			}
		}else { //如果没有ID为MESSAGE_SOURCE_BEAN_NAME的组件 
			DelegatingMessageSource dms = new DelegatingMessageSource(); //创建一个message组件
			dms.setParentMessageSource(getInternalParentMessageSource());
			this.messageSource = dms;
                //将messageSource注入容器
			beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
						"': using default [" + this.messageSource + "]");
			}
		}
	}

initMessageSource方法的执行流程:

  1.  获取BeanFactory
  2. 看容器中是否有id为messageSource的,类型是MessageSource的组件。                                                                                        如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource;                                                                   MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取;
  3. 把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;
     beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);    
     MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale);

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

	protected void initApplicationEventMulticaster() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
                //从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}else {//如果beanFactory中没有注册,创建一个SimpleApplicationEventMulticaster
			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 + "]");
			}
		}
	}

initApplicationEventMulticaster方法的执行流程:

  1.   获取BeanFactory
  2.  从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
  3.  如果上一步没有配置;创建一个SimpleApplicationEventMulticaster
  4.  将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入

9、onRefresh();留给子类,重写该方法,自定义逻辑。

	protected void onRefresh() throws BeansException {
		
	}

10、registerListeners();将所有的ApplicationListener注册进容器;

	protected void registerListeners() {
		//注册静态监听器ApplicationListener
		for (ApplicationListener<?> listener : getApplicationListeners()) {
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		//获取所有的ApplicationListener组件
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
                //将监听器派发到事件拍发器中
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		//获取并派发事件
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (earlyEventsToProcess != null) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

registerListeners方法工作流程:

  1.  从容器中拿到所有的ApplicationListener
  2. 将每个监听器添加到事件派发器中; getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  3. 派发之前步骤产生的事件;

11、finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean;

finishBeanFactoryInitialization方法主要用来创建注册经容器中的单例bean,也是SpringIOC的核心方法,关于该方法的解释可参考博客:Spring IOC源码解析_三水写代码的博客-CSDN博客

12、finishRefresh();完成BeanFactory的初始化创建工作;IOC容器就创建完成;

	protected void finishRefresh() {
		// 初始化此上下文的生命周期处理器。
		initLifecycleProcessor();

		// 首先将refresh传播到生命周期处理器。
		getLifecycleProcessor().onRefresh();

		//发布最终事件。
		publishEvent(new ContextRefreshedEvent(this));

		//向容器中注册spring.liveBeansView.mbeanDomain
		LiveBeansView.registerApplicationContext(this);
	}

finishRefresh方法的工作流程:

  1. 初始化LifecycleProcessor后置处理器(生命周期后置处理器)
  2. 获取LiftcycleProcessor,执行onRefresh()方法
  3. 发布事件
  4. 向容器中注册mbeanDomain

initLifecycleProcessor:

	protected void initLifecycleProcessor() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
       //public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
		if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
			this.lifecycleProcessor =
					beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
			if (logger.isDebugEnabled()) {
				logger.debug("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.isDebugEnabled()) {
				logger.debug("Unable to locate LifecycleProcessor with name '" +
						LIFECYCLE_PROCESSOR_BEAN_NAME +
						"': using default [" + this.lifecycleProcessor + "]");
			}
		}
	}

initLifecycleProcessor的工作流程:

  1. 获取所有的beanFactory;
  2. 检查获取的beanFactory中是否包含LifecycleProcessor;
  3. 如果没有LifecycleProcessor,则创建并注入一个DefaultLifecycleProcessor

getLifecycleProcessor().onRefresh():

	private LifecycleProcessor lifecycleProcessor;


	LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
		if (this.lifecycleProcessor == null) {
			throw new IllegalStateException("LifecycleProcessor not initialized - " +
					"call 'refresh' before invoking lifecycle methods via the context: " + this);
		}
		return this.lifecycleProcessor;
	}


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

getLifecycleProcessor().onRefresh(),先获取容器中的LifecycleProcessor,然后执行onRefresh()方法。而onRefresh方法中直接调用了startBeans方法。

startBeans:

	private void startBeans(boolean autoStartupOnly) {
		Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
		Map<Integer, LifecycleGroup> phases = new HashMap<Integer, LifecycleGroup>();
		for (Map.Entry<String, ? extends Lifecycle> entry : lifecycleBeans.entrySet()) {
			Lifecycle bean = entry.getValue();
			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(entry.getKey(), bean);
			}
		}
		if (!phases.isEmpty()) {
			List<Integer> keys = new ArrayList<Integer>(phases.keySet());
			Collections.sort(keys);
			for (Integer key : keys) {
				phases.get(key).start();
			}
		}
	}

startBeans方法中,先获取容器中的Lifecycle实例对象,将Lifecycle分组执行。

总结:

    1)、Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息;
              1)、xml注册bean;<bean>
              2)、注解注册Bean;@Service、@Component、@Bean、xxx
    2)、Spring容器会合适的时机创建这些Bean
              1)、用到这个bean的时候;利用getBean创建bean;创建好以后保存在容器中;
              2)、统一创建剩下所有的bean的时候;finishBeanFactoryInitialization();
    3)、后置处理器;BeanPostProcessor
              1)、每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能;
                        AutowiredAnnotationBeanPostProcessor:处理自动注入
                       AnnotationAwareAspectJAutoProxyCreator:来做AOP功能;
                       xxx....
                      增强的功能注解:
                              AsyncAnnotationBeanPostProcessor
                              ....
    4)、事件驱动模型;
              ApplicationListener;事件监听;
              ApplicationEventMulticaster;事件派发:

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐