調(diào)用SpringApplication.run方法
/**
* Created by dwz on 2019/7/31.
*/
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.youyou")
public class SpringbootStart {
public static void main(String[] args) {
SpringApplication.run(SpringbootStart.class);
}
}
對run方法總結(jié)如下:
1.獲取創(chuàng)建SpringApplicationRunListener
2.創(chuàng)建參數(shù)牙甫,配置Enviroment
3.創(chuàng)建ApplicationContext
4.初始化ApplicationContext,加載Enviroment
5.refresh,加載各種bean
6.由 SpringApplicationRunListener 來發(fā)出 running 消息蒙秒,告知程序已運(yùn)行起來了
下面對refresh方法總結(jié):
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1.刷新前準(zhǔn)備工作载碌,包括設(shè)置啟動時(shí)間,是否激活標(biāo)識位懂诗,初始化屬性源(property source)配置
prepareRefresh();
// 2.創(chuàng)建beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//3.準(zhǔn)備創(chuàng)建好的beanFactory(給beanFactory設(shè)置ClassLoader,注冊AOP相關(guān)的一些東西,注冊環(huán)境相關(guān)的一些bean
prepareBeanFactory(beanFactory);
try {
//4. 模板方法孵睬,為容器某些子類擴(kuò)展功能所用(工廠后處理器)這里可以參考BeanFactoryPostProcessor接口的postProcessBeanFactory方法
postProcessBeanFactory(beanFactory);
//5.調(diào)用所有BeanFactoryPostProcessor注冊為Bean
invokeBeanFactoryPostProcessors(beanFactory);
//6.注冊所有實(shí)現(xiàn)了BeanPostProcessor接口的Bean
registerBeanPostProcessors(beanFactory);
// 7.初始化MessageSource,和國際化相關(guān)
initMessageSource();
// 8.初始化容器事件傳播器
initApplicationEventMulticaster();
// 9.調(diào)用容器子類某些特殊Bean的初始化,模板方法
onRefresh();
// 10.為事件傳播器注冊監(jiān)聽器
registerListeners();
// 11.初始化所有剩余的bean(普通bean)
finishBeanFactoryInitialization(beanFactory);
// 12.初始化容器的生命周期事件處理器伶跷,并發(fā)布容器的生命周期事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 13.銷毀已創(chuàng)建的bean
destroyBeans();
// 14.重置`active`標(biāo)志
cancelRefresh(ex);
throw ex;
}
finally {
//重置一些緩存
resetCommonCaches();
}
}
}
1.創(chuàng)建beanFactory
2.調(diào)用所有BeanFactoryPostProcessor注冊為Bean
3.初始化MessageSource,和國際化相關(guān)
4.初始化所有剩余的bean(普通bean)
整體流程圖如下: