Spring框架源码--顶层初始化

1.启动入口

  • org.springframework.web.context.ContextLoaderListener,它实现了Tomcat容器的ServletContextListener接口,所以它与普通的Servlet监听一样。重写到两个方法:contextInitialized()方法在web容器初始化时执行,contextDestroyed()方法在容器销毁时执行。
ContextLoaderListener#contextInitialized
ContextLoader#initWebApplicationContext
ContextLoader#configureAndRefreshWebApplicationContext
AbstractApplicationContext#refresh

2. 顶层 AbstractApplicationContext#refresh

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			//供子类重写个性化配置使用
			prepareRefresh();
			//初始化beanFactory,并进行注解、xml等方式的bean加载
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
			prepareBeanFactory(beanFactory);

			try {
				//供子类重写以实现个性化功能
				postProcessBeanFactory(beanFactory);
				invokeBeanFactoryPostProcessors(beanFactory);
				registerBeanPostProcessors(beanFactory);
				//初始化message源,比如语言、国际化
				initMessageSource();
				initApplicationEventMulticaster();
				//留给子类初始化个性的bean
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();
				finishBeanFactoryInitialization(beanFactory);
				finishRefresh();
			}catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +"cancelling refresh attempt: " + ex);
				}
				destroyBeans();
				cancelRefresh(ex);
				throw ex;
			}finally {
				resetCommonCaches();
			}
		}
	}

2.BeanFactory初始化:AbstractApplicationContext#obtainFreshBeanFactory

AbstractRefreshableApplicationContext#refreshBeanFactory
//确保只有一个beanFactory
if (hasBeanFactory()) {
	destroyBeans();
	closeBeanFactory();
}
//定制化  设置是否覆盖bean、是否允许循环依赖等
customizeBeanFactory(beanFactory); 
//四种不同的加载策略(注解、xml等,默认后面覆盖前面,因此xml最后)
loadBeanDefinitions(beanFactory);

3. 初始化注解方式beanFactory

  • AnnotationConfigWebApplicationContext#loadBeanDefinitions
//之前生成beanName,然后先加载单例的bean生成器()
beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);

你可能感兴趣的:(服务端开发,spring)