Spring【版本5.2.2】容器初始化过程(二)refresh(一)

下面来说说AnnotationConfigApplicationContext的第三个方法 refresh

	/**
	 * 准备好bean工厂,实例化对象
	 * @throws BeansException
	 * @throws IllegalStateException
	 */
	@Override
	public void refresh() throws BeansException, IllegalStateException {

		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			// 调用容器准备初始化方法,获取容器的当前时间,同时给容器设置同步标识,是否激活标示位,
			// 初始化属性源(property source)配置,还有各种Map,比如earlyApplicationListeners、
			// earlyApplicationEvents、applicationListeners
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory[告诉子类,刷新内部工厂].
			// 告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入从子类的refreshBeanFactory()方法启动
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			// 为beanFactory配置容器特性,例如类加载器、时间处理器、环境变量等等
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				// 为容器的某些子类指定特殊的BeanPost事件处理器,空方法,可能会在web等等其他模块用到,
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				// 调用所有注册的BeanFactoryPostProcessor的Bean
				// 在spring的环境中取执行被注册的factory processors,
				// 设置执行自定义的ProcessBeanFactory和spring内部定义的
				// 例如:ConfigurationClassPostProcessor(6大BD其中之一,其他五个不是)
				// 偷偷的笑了,这个方法,网上应该有一大坨的文章,我们也当成一个独立的文章来吧,东西实在是太多了
				// 本着实战注意,还是要自己断点走一遍,具体见后面的Spring容器初始化过程(三)
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				// 2、得到spring内部自己维护的BeanDefinitionRegistryPostProcessor
				// 为BeanFactory注册BeanPost事件处理器.
				// BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件
				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();
			}
		}
	}
1. prepareRefresh

调用容器准备初始化方法,获取容器的当前时间,同时给容器设置同步标识,是否激活标示位,初始化属性源(property source)配置,还有各种Map,比如earlyApplicationListeners、
earlyApplicationEvents、applicationListeners

2. obtainFreshBeanFactory 方法

告诉子类刷新内部bean工厂。其实他啥都不在做,就是先判断是否已经refreshed然后设置他,然后赋值serializationId

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	 	// 先判断是否已经refreshed,然后赋值serializationId
	 	// 当前beanFactory的id和displayName:org.springframework.context.annotation.AnnotationConfigApplicationContext@4563e9ab
		refreshBeanFactory();
		return getBeanFactory();
	}
3. prepareBeanFactory 说明

配置其标准的特性,比如上下文加载器ClassLoader和post-processors回调

    /**
	 * 配置其标准的特性,比如上下文加载器ClassLoader和post-processors回调
	 * Configure the factory's standard context characteristics,
	 * such as the context's ClassLoader and post-processors.
	 * @param beanFactory the BeanFactory to configure
	 */
	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		// 添加一个类加载器
		beanFactory.setBeanClassLoader(getClassLoader());
		// 添加bean表达式解释器,为了能够让我们的beanFactory去解析bean表达式
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

		// 对象与String相互转换 比如 <property red="dao">
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		// 添加一个后置处理器ApplicationContextAwareProcessor
		// 能够在bean中获得各种Aware(*Aware都有其作用)
		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.
		// 添加了一个ApplicationListenerDetector后置处理器
		// 该BeanPostProcessor检测那些实现了接口ApplicationListener的bean,在它们创建时初始化之后,
		// 将它们添加到应用上下文的事件多播器上;并在这些ApplicationListener bean销毁之前,将它们从应用上下文的事件多播器上移除。
		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[注册默认环境bean].
		/* 如果自定义Bean中没有"environment"、"systemProperties"和"systemEnvironment"的bean,则注册这两个Bean
		 * Key为"environment"、"systemProperties"和"systemEnvironment",Value为Map。
		 * 这两个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());
		}
	}

继续感谢子路老师,未完待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值