Spring IOC启动过程
以ClassPathXmlApplicationContext为例:
构造方法:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
refresh()方法
主要有四步:
①启动,记录时间和检验xml文件
②解析XML文件,将bean信息放入beanDefinitionMap中
③设置Bean类加载器和加载特殊的bean
④完成初始化bean,根据bean的作用域来创建对象
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
//①启动,记录时间和检验xml文件
this.prepareRefresh();
//②解析XML文件,将bean信息放入beanDefinitionMap中
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
//③设置Bean类加载器和加载特殊的bean
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
//④完成初始化bean,根据bean的作用域来创建对象
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}