main函数中通过SpringApplication类的静态方法run()开始流程,SpringApplication类首先将main函数所在的类作为primarySource来初始化一个SpringApplication的实例,作为primarySource是指“load beans from the specified primary sources”,SpringApplication实例化包括的流程有:
// 使用startupShutdownMonitor加锁 // 对startup和close过程中的refresh和destory bean的过程加锁 synchronized (this.startupShutdownMonitor) { // prepareRefresh // 留下了一个protected的initPropertySources()方法,可以实现子类来Replace any stub property sources with actual instances. // 然后验证标记为required的property // Prepare this context for refreshing. prepareRefresh();
// 初始化bean factory // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactorybeanFactory= obtainFreshBeanFactory();
// 设置ClassLoader、ignoreDependency等 // 注册early post-processor for detecting inner beans as ApplicationListeners // 注册environment、systemProperties、systemEnvironment bean // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory);
try { // protected方法,可以实现动态的添加、修改bean等操作 // “Modify the application context's internal bean factory after its standard initialization.” // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory);
// 调用各个BeanFactoryPostProcessor // 调用BeanDefinitionRegistryPostProcessor来加载所有的BeanDefination,比如使用ConfigurationClassPostProcessor来加载所有@Configuration的类 // 比如,ConfigFileApplicationListener在onApplicationPreparedEvent事件时添加了PropertySourceOrderingPostProcessor,如果defaultProperties存在,此时将其移动到list的最后 // BeanFactoryPostProcessor是在加载了BeanDefination之后、bean实例化之前调用的 // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory);
// MessageSource,用于国际化等 // Initialize message source for this context. initMessageSource();
// Initialize event multicaster for this context. initApplicationEventMulticaster();
// onRefresh(),protected方法,可以在子类中实现initialize other special beans // 对于servlet应用,实现的子类中调用了createWebServer()来读取配置、创建Tomcat web server // Initialize other special beans in specific context subclasses. onRefresh();
// Check for listener beans and register them. registerListeners();