淘先锋技术网

首页 1 2 3 4 5 6 7


记录一下最近学的Spring容器创建过程。

1. 流程(源码解析)

1、AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(ExConfig.class);

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
		//this(),本类的无参构造方法,会默认调用父类的无参构造器创建bean工厂
		//this.beanFactory = new DefaultListableBeanFactory()
		this();
		register(componentClasses);
		//刷新容器
		refresh();
	}

2、refresh()

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			//刷新前的预处理
			prepareRefresh();

			//刷新获取beanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			//beanFactory的预准备工作
			prepareBeanFactory(beanFactory);

			try {
				//beanFactory完成后进行的后置处理
				postProcessBeanFactory(beanFactory);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				//执行BeanFactoryPostProcessor
				invokeBeanFactoryPostProcessors(beanFactory);

				//注册BeanPostProcessor(Bean的后置处理器)
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

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

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

				//留给子类重写的
				onRefresh();

				//注册所有的ApplicationListener
				registerListeners();

				//实例化所有的单实例bean
				finishBeanFactoryInitialization(beanFactory);

				//完成Refresh
				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 {
				resetCommonCaches();
				contextRefresh.end();
			}
		}
	}

下面对refresh的各个方法进行介绍

2.1 刷新前的预处理: prepareRefresh()

protected void prepareRefresh() {
		//设置一些属性,转化为激活状态
		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());
			}
		}

		//初始化上下文环境中的任何占位符属性源
		//空方法,留给子类继承然后重写
		initPropertySources();

		//对自定义属性的一些校验
		getEnvironment().validateRequiredProperties();

		//创建早期的监听list
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
			//重新设置
			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<>();
	}

2.2 获取beanFactory: ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//刷新beanFactory
		refreshBeanFactory();
		//获取beanFactory
		return getBeanFactory();
	}

2.2.1、refreshBeanFactory

@Override
	//设置序列化id,BeanFactory是一开始调用父类无参构造创建的
	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());
	}

2.2.2、return getBeanFactory()
返回一开始调用父类无参构造创建的beanFactory : DefaultListableBeanFactory


2.3 prepareBeanFactory(beanFactory): beanFactory的预准备工作

总结起来就是在beanFactory中设置了一大堆东西

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		//设置类的加载器
		beanFactory.setBeanClassLoader(getClassLoader());
		if (!shouldIgnoreSpel) {
			//设置bean的表达式解析器
			beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		}
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		//添加部分BeanPostProcessor:ApplicationContextAwareProcessor
		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.ignoreDependencyInterface(ApplicationStartup.class);

		//注册可以解析的自动装配,我们可以在任何地方注入
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		//设置添加bean的后置处理器:ApplicationListenerDetector
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		//设置和aspectj相关的支持:loadTimeWeaver
		if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			//添加后置处理器
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			//为类型匹配设置临时ClassLoader。
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}

		//注册一些默认的与环境相关的单实例bean
		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());
		}
		if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
			beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
		}
	}

2.4 beanFactory完成后进行的后置处理: postProcessBeanFactory(beanFactory);

空方法,留给子类继承重写,可以自己添加一些自己需要的配置在里面。子类通过重写这个方法来在BeanFactory创建并预准备完成以后作进一步的设置

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	}

2.5 invokeBeanFactoryPostProcessors(beanFactory): 执行BeanFactoryPostProcessor

1、执行所有的BeanFactoryPostProcessor:beanFactory的后置处理器,在bean创建并准备完成后执行
2、判断,如果成立就添加一个LoadTimeWeaverAwareProcessor和一个ContextTypeMatchClassLoader组件。

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

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

1、执行所有的BeanFactoryPostProcessor: invokeBeanFactoryPostProcessors 代码有点多:直接上总结流程

(1)判断beanFactory是不是BeanDefinitionRegistry类型的(默认是true的)
(2)先获取到所有的BeanDefinitionRegistryPostProcessor
(3)通过优先级先后执行所有的BeanDefinitionRegistryPostProcessor
     1、首先是执行实现了PriorityOrdered接口的,先加入到     currentRegistryProcessors中,然后排序,再加入到registryProcessors中,依次执行BeanDefinitionRegistryPostProcessor方法
     2、在执行实现了Ordered顺序接口的BeanDefinitionPostPeocessor,流程和上面的一模一样,postProcessor.postProcessBeanDefinitionRegistry(registry)
     3、最后一步,执行没有实现任何优先级或者顺序接口的BeanDefinitionRegistryPostProcessor。postProcessor.postProcessBeanDefinitionRegistry(registry)

(4)再通过优先级先后执行所有的BeanFactoryPostProcessor,流程和上面第(3)步一样。都是判断类型,排序,执行。


2.6 registerBeanPostProcessors: 注册bean的后置处理器

总的来说就是根据接口先后注册bean的后置处理器。
(1)先是实现PriorityOrdered接口的
(2)然后是实现Order接口的
(3)其次是没有接口的
(4)最后是实现MergeBeanDefinitionPostProcessor的。
(5)在最终还注册了一个ApplicationListener的探测器,用于检测后续注册的bean是不是ApplicationListener类型的。

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

		
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		//创建不同的list分别存储不同类型的beanPostProcessor
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
		    //首先判断是不是PriorityOrdered类型的
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				//添加进priorityOrderedPostProcessors的list中
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			//其次添加Ordered类型的
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				//最后再添加没有实现排序接口类型的
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// 首先注册priorityOrdered接口类型的bean后置处理器
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// 其次,注册实现Order接口的bean后置处理器,在注册之前做一些处理
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			//判断是不是MergedBeanDefinitionPostProcessor类型的
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				//如果是就添加进internalPostProcessors:内部bean后置处理器
				internalPostProcessors.add(pp);
			}
		}
		//排序并注册
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		//最后,注册所有常规的bean,没有实现Ordered等接口的bean
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			//一样判断是不是MergedBeanDefinitionPostProcessor类型的
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		//进行注册
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		//最后。注册所有的internalPostProcessors,也就是注册MergedBeanDefinitionPostProcessor类型的后置处理器
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		//注册一个ApplicationListener的探测器,用于监听注册的bean是不是application类型的
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

2.7 initMessageSource():初始化MessageSource组件(国际化功能:消息绑定、消息解析、

protected void initMessageSource() {
		//获取beanFactory
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		//判断beanFactory中是否包含id为messageSource的组件
		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
			//如果是,就赋值
			this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
			//同样判断messageSource是不是HierarchicalMessageSource类型的
			if (this.parent != null && this.messageSource instanceof 
			HierarchicalMessageSource) {
				//如果是,就强制转换
				HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
				//设置父类的messageSource 或者直接以父类作为messageSource
				if (hms.getParentMessageSource() == null) {
					hms.setParentMessageSource(getInternalParentMessageSource());
				}
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Using MessageSource [" + this.messageSource + "]");
			}
		}
		else {
			//如果没有这个组件,就new一个DelegatingMessageSource
			//然后以id为messageSource进行注册,添加到beanFactory中
			DelegatingMessageSource dms = new DelegatingMessageSource();
			dms.setParentMessageSource(getInternalParentMessageSource());
			this.messageSource = dms;
			beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
			if (logger.isTraceEnabled()) {
				logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
			}
		}
	}

2.8 initApplicationEventMulticaster(): 初始化事件派发器

protected void initApplicationEventMulticaster() {
		//获取beanFactory
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		//判断是否有id为applicationEventMulticaster的时间派发器
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
			//如果有,就直接赋值
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isTraceEnabled()) {
				logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
			//如果没有,就new一个SimpleApplicationEventMulticaster
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			//然后,以id为applicationEventMulticaster注册到beanFactory中
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
			if (logger.isTraceEnabled()) {
				logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
						"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
			}
		}
	}

2.9 onRefresh() :空方法

用于给子类重写,然后可以自己注册一些组件进去…

	protected void onRefresh() throws BeansException {
		// For subclasses: do nothing by default.
	}

2.10: registerListeners(): 注册ApplicationListener监听器

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

		//这里获取所有的ApplicationListenerBean,添加到事件派发器中
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		//派发之前步骤产生的早期事件
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

2.11: finishBeanFactoryInitialization(beanFactory): 实例化所有的单实例bean

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		//初始化转换服务:id为conversionService
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		//这部分不太清楚,看意思应该是注册解析注解属性的解析器
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		//提前初始化LoadTimeWeaverAware,可以提前注册它们的转换器
		//aspectj相关
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}
		
		//停止使用临时的类加载器进行类型匹配
		beanFactory.setTempClassLoader(null);

		//设置允许缓存所有的bean定义信息,不希望再发生改变。也就是bean的信息定义成什么样就什么样了
		beanFactory.freezeConfiguration();

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

关键: beanFactory.preInstantiateSingletons()
(1)获取所有的bean名字:new ArrayList<>(this.beanDefinitionNames)
(2)根据bean的名字获取所有bean:String beanName : beanNames
(3)获取bean的定义信息RootBeanDefinition:RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName)
(4)判断是不是非抽象的、单例的、和不是懒加载的

     1、判断是否是FactoryBean,也就是说判断是不是实现FactoryBean接口的bean
     2、不是工厂bean,就调用getBean(beanName)来创建对象,等于ioc.getBean()
        (1)调用doGetBean(name, null, null, false)
        (2)doGetBean方法中首先获取转化过后的bean的名字,比如去掉一些前缀
        (3)根据名字获取缓存中保存的单实例bean,如果能获取到,说明被创建过(所有创建过的单实例bean都会被缓存起来),缓存的Map是:
          private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
        (4)如果缓存(Map中)获取不到,就开始创建bean
        (5)首先判断有没有父工厂(父子容器相关的)
        (6)markBeanAsCreated(beanName),标记当前bean被创建了,防止多线程创建多个bean等
        (7)RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName),拿到bean的定义信息,判断是不是抽象类,如果是就抛异常throw new BeanIsAbstractException(beanName)
        (8)String[] dependsOn = mbd.getDependsOn(),获取所有bean依赖的其他bean,如果有就调用getBean创建 => getBean(dep)。
        (9) 启动单实例bean的创建流程=>createBean(beanName, mbd, args),
            1、拿到bean的定义信息,解析bean的类型…
            2、Object bean = resolveBeforeInstantiation(beanName, mbdToUse),先提前拦截返回代理对象 内部判断是不是InstantiationAwareBeanPostProcessor类型的,如果是就触发
postProcessBeforeInstantiation方法,再判断这个方法返回值是不是空,如果不是, 就触发postProcessAfterInitialization方法。(实际上这里并不会产生代理对象
的)
            3、如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象,就会调用Object beanInstance = doCreateBean(beanName, mbdToUse, args)创建bean,创建过程如下:
                (1)首先判断是不是单实例,如果是就从缓存中移除
                (2)instanceWrapper = createBeanInstance(beanName, mbd, args):创建bean实例, 这个方法调用完之后,bean的对象就出来了。内部调用工厂方法或者利用对象构造器创建bean实例
                (3)applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName),调用后置处理器来处理bean的定义信息内部调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName)方法
                (4)populateBean(beanName, mbd, instanceWrapper):为Bean属性赋值。
                     1、在第(2)步实例化之后拿到InstantiationAwareBeanPostProcessor的后置处理器,执行它的 postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)方法后置处理
                     2、从缓存中拿到InstantiationAwareBeanPostProcessor后置处理器,执行postProcessPropertyValues方法,相当于把属性存起来,给后面真正赋值用
                     3、应用Bean属性的值, applyPropertyValues(beanName, mbd, bw, pvs),内部使用各种set方法进行赋值
                (5)exposedObject = initializeBean(beanName, exposedObject, mbd):初始化bean
                     1、invokeAwareMethods(beanName, bean),执行xxxAware接口的方法,内部判断是不是BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口的,如果是就设置
                     2、applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName):执行后置处理器执行初始化之前的方法,这一步证明还没真正初始化
                     3、invokeInitMethods(beanName, wrappedBean, mbd), 执行初始化方法
                         (1) 是否是InitializingBean接口的实现,如果是就执行接口规定的初始化
                         (2) String initMethodName = mbd.getInitMethodName() 判断是否是自定义的初始化方法,如果是,内部反射invoke调用初始化方法.
                     4、wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName),执行后置处理器初始化之后的方法,内部调用postProcessAfterInitialization方法。
                (6) registerDisposableBeanIfNecessary(beanName, bean, mbd),注册Bean的销毁方法,比如注册一些销毁接口…


(5)preInstantiateSingletons的最后一步=>所有bean都利用getBean创建完成以后的流程:检查所有的bean是否是SmartInitializingSingleton接口的,如果是,就执行smartSingleton.afterSingletonsInstantiated()方法,比如EventListener


2.12 finishRefresh(): 完成beanFactory的初始化创建工作,完成后IOC容器就创建完成了

protected void finishRefresh() {
		//清除一些资源缓存,例如ASM
		clearResourceCaches();

		//初始化和生命周期有关的后置处理器,内部获取id为lifecycleProcessor的组件
		//如果没有,就调用方法创建一个id为lifecycleProcessor的DefaultLifecycleProcessor
		initLifecycleProcessor();

		
		getLifecycleProcessor().onRefresh();

		//发布容器刷新完成事件,流程就是使用派发器派发ApplicationListener
		publishEvent(new ContextRefreshedEvent(this));

		if (!NativeDetector.inNativeImage()) {
			LiveBeansView.registerApplicationContext(this);
		}
	}



2. 小结

spring创建过程中最重要的就是refresh()过程,

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			//刷新前的预处理
			prepareRefresh();

			//刷新获取beanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			//beanFactory的预准备工作
			prepareBeanFactory(beanFactory);

			try {
				//beanFactory完成后进行的后置处理
				postProcessBeanFactory(beanFactory);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				//执行BeanFactoryPostProcessor
				invokeBeanFactoryPostProcessors(beanFactory);

				//注册BeanPostProcessor(Bean的后置处理器)
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

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

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

				//留给子类重写的
				onRefresh();

				//注册所有的ApplicationListener
				registerListeners();

				//实例化所有的单实例bean
				finishBeanFactoryInitialization(beanFactory);

				//完成Refresh
				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 {
				resetCommonCaches();
				contextRefresh.end();
			}
		}
	}

在其中主要关注的是finishBeanFactoryInitialization,我们容器中所有的单实例对象如果还没创建的就在这个时候创建。当然还有很多的后置处理器BeanPostProcessor,每一个bean创建完成之后会调用该方法来对bean做一些处理增强。比如Aop相关的,Autowire相关的。

当然,这里面也没有各个细节都涉及到,尽量包含spring容器创建、初始化的一些重要步骤,最重要的还是debug。自己动手debug几次,就能了解个大概流程了。






如有错误,欢迎指出