ClassPathXmlApplicationContext acx = new ClassPathXmlApplicationContext("spring.xml");
这行代码执行完整个ioc生命周期就结束了。
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException { //调用父类执行一些初始化操作,包括初始化系统环境 super(parent); //设置解析文件的路径,这里的路径可以包括表达式,会从spring的环境变量里面解析后替换 this.setConfigLocations(configLocations); if (refresh) { //最核心的生命周期步骤 this.refresh(); } }
//13个生命周期核心步骤
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. //准备环境和一些初始化操作 prepareRefresh(); // Tell the subclass to refresh the internal bean factory. //解析xml配置包括bean,alias等系统定义的标签和自定义的标签例如 <context:component-scanner/>然后把解析的标签生生成beandefiniton,把bd放入beanfactory,下一节会详细分析 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. //注入bfpp postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. //这行bfpp invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. //注入bpp registerBeanPostProcessors(beanFactory); // Initialize message source for this context. //初始化国际化 initMessageSource(); // Initialize event multicaster for this context. //初始化消息监听事件等 initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. //执行刷新操作,留给子类完成 onRefresh(); // Check for listener beans and register them. //注入监听器 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. //完成bean的实例化和初始化包括循环依赖等操作 finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. //完成刷新工作,包括事件监听等 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(); } } }