0
点赞
收藏
分享

微信扫一扫

spring源码第一篇:总览refresh

程序员阿狸 2022-02-23 阅读 61
spring
public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

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

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

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

以上是spring 5.1版本的容器启动refresh方法,一共12个方法,接下来我会每个方法挨个阅读,首先总览总体:

1、refresh前的准备工作

prepareRefresh()

启动时间,关闭标志,启动标志,初始化属性资源,获取标准环境对象并验证必须的属性,初始化应用监听器和事件集合

2、构建beanFactory

obtainFreshBeanFactory()

生成DefaultListableBeanFactory的bean工厂

3、工厂各种设置以及初始化

prepareBeanFactory(beanFactory)

包括设置bean的classloader,表达式解析器,忽略依赖接口,注册默认的environment等等

4、beanFactory增强器,扩展点

postProcessBeanFactory

5、调用增强方法

invokeBeanFactoryPostProcessors

6、注册bean的增强器

7、初始化消息源

8、初始化事件多播器

9、初始化其他bean,扩展点

onRefresh

10、注册监听器

11、完成bean工厂初始化

12、发布相应事件

举报

相关推荐

0 条评论