Spring基础--整合MVC配置 (二)

2014-11-24 02:04:05 · 作者: · 浏览: 1
tInitParameter(CONFIG_LOCATION_PARAM);
if (configLocation != null) {
wac.setConfigLocations(StringUtils.tokenizeToStringArray(configLocation,
ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
其中CONFIG_LOCATION_PARAM是该类的常量,其值为contextConfigLocation。可看出:ContextLoader首先检查servletContext中是否有contextConfigLocation的参数,如果有该参数,则加载该参数指定的配置文件。带多参数的配置如下:


contextConfigLocation

/WEB-INF/daoContext.xml,/WEB-INF/applicationContext.xml



context
org.springframework.web.context.ContextLoaderServlet

1

总结:
ContextLoaderServlet与ContextLoaderListener底层都依赖于ContextLoader。
因此,二者唯一的区别:是由于Servlet2.3的规范:listener比servlet优先加载。
因此,采用ContextLoaderListener创建ApplicationContext的时机更早。

当然,也可以通过ServletContext的getAttribute方法获取ApplicationContext,使用WebApplicationContextUtils类更便捷,因为无需记住ServletContext属性名。
即使ServletContext的WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE属性没有对应对象,WebApplicationContextUtils的getWebApplicationContext()方法将会返回空,而不会引起异常。

获得了WebApplicationContext实例的引用后,可以通过bean的名字访问容器中的bean实例。
大部分时候,无需通过这种方式访问容器中的bean。因为Spring容器将bean置入容器的管理中,客户端请求直接转发给容器中的bean,然后由容器管理bean之间的依赖。