上一篇博文SPRing源码之ContextLoaderListener(1)介绍了ContextLoaderListener加载过程,最终要的部分就是如何加载我们指定的applicationContext.xml没写,本片博文将展开来讲
还记得ServletContextListener主要执行的contextInitalized(event)主要执行逻辑吗?
//读取ContextLoader.properties获取XmlWebApplicationContext//通过反射获取webApplicationContext实例this.context = this.createWebApplicationContext(servletContext);//加载配置文件(最关键的、最复杂部分)this.configureAndRefreshWebApplicationContext(err, servletContext);//将WebApplicationContext放入到ServletContext中servletContext.setAttribute("org.springframework.web.context.WebApplicationContext.ROOT", this.context);//加载bean配置的方法 ContextLoader.configureAndRefreshWebApplicationContext(err, servletContext)方法的执行
web.xml中有一行配置,在这个方法中就有体现
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/spring/applicationContext*.xml</param-value></context-param>主要代码如下
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {//看到这行很激动吗?web.xml中配置的参数吗哈哈String configLocationParam = sc.getInitParameter("contextConfigLocation");//重头戏就是这个方法WebAcpplicationContext.refresh()wac.refresh();}wac的一个父类AbstractApplicationContext 该类中定义的refresh()是一个模板方法,部分需要子类来重写
public void refresh() throws BeansException, IllegalStateException { Object var1 = this.startupShutdownMonitor; synchronized(this.startupShutdownMonitor) { this.prepareRefresh(); ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); this.prepareBeanFactory(beanFactory); try { this.postProcessBeanFactory(beanFactory); this.invokeBeanFactoryPostProcessors(beanFactory); this.registerBeanPostProcessors(beanFactory); this.initMessageSource(); this.initApplicationEventMulticaster(); this.onRefresh(); this.registerListeners(); this.finishBeanFactoryInitialization(beanFactory); this.finishRefresh(); } catch (BeansException var9) { //... } finally { this.resetCommonCaches(); } } }内容比较多一个个的来看
新闻热点
疑难解答