经过无数次debug Spring源码,对spring整体启动过程有了大致了解。因为spring体系太过复杂,我也没用能力把spring讲的面面俱到并且没用错误。要想掌握spring的细节,还需要自己去debug源码。spring的启动方式很很多比如通过springboot配置去启动,或者通过ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-provider.xml"});
context.start(); 这样的代码去启动都是可以的,不同启动方式获取启动资源的方式不同,但是他们都会调用AbstractApplicationContext.refresh()方法,因为AbstractApplicationContext是所有ApplicationContext的父类。
AbstractApplicationContext.refresh()方法是spring启动的核心,下面我们对这个方法大致介绍下(见下面代码)。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//记录启动时间,并将启动状态改为active
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//创建beanFactory,并将所有的bean读取出来并组装成beanDefinition加入到beanFactory中,关于读取bean有多种方式,比如从xml中读取配置的bean, 也可以像springboot配置扫描的方式来读取bean.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 深入配置factory,比如设置ignoreDependencyInterface,addPropertyEditorRegistrar等,此外注册一些和环境相关的bean如environment,systemProperties,systemEnvironment
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//什么也没用做,设计让子类去扩展处理beanFactory
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 处理并调用BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessors
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//处理并调用BeanPostProcessors
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 注册messageSource其用于解析message
initMessageSource();
// Initialize event multicaster for this context.
// 注册applicationEventMulticaster为bean,如果未指定将会默认使用new SimpleApplicationEventMulticaster(beanFactory)
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 什么也没用做,设计让子类去扩展,比如要提早实例化指定的bean等
onRefresh();
// Check for listener beans and register them.
// 发现并将ApplicationListener添加到applicationEventMulticaster,如果有需要提前发布的ApplicationEvent则对他们进行广播ApplicationEventMulticaster().multicastEvent(earlyEvent)
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 最重要的一步,实例化所有的bean以及进行bean处理器处理,以及对factoryBean进行深入实例化依赖注入,属性填充等。此外还会对SmartInitializingSingleton实例化后进行相应的处理
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 1:注册lifecycleProcessor为bean,
//2:对所有实现Lifecycle接口(一般地SmartLifecycle接口比较常用)的类做处理进行生命周期的管理(比如启动相应的bean)。
//3:发布ApplicationEvent给ApplicationListener做监听,例如dubbo的ServiceBean<T>就实现了ApplicationListener<ContextRefreshedEvent>,所以DUBBO的暴露服务就是在这个方法里面执行的。
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();
}
}
}
这里只是大致介绍下各个方法的功能,如果想深入了解各个方法可以自己去debug