1、通过web.xml中的监听器ContextLoadListener加载Spring容器,实际情况中亦可以根据项目需要自定义一个Listener去继承该监听器,以增强其方法实现(对session管理等);
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2、ContextLoadListener首先调用其contextInitialized()方法对Spring应用上下文进行初始化,在ContextLoader类的static静态块中,通过加载ContextLoader.properties属性文件,反射出XmlWebApplicationContext上下文;
public void contextInitialized(ServletContextEventevent) {
initWebApplicationContext(event.getServletContext());
}
static {
try {
ClassPathResourceresource = new ClassPathResource("ContextLoader.properties", ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException ex) {
thrownew IllegalStateException("Could not load 'ContextLoader.properties': " +ex.getMessage());
}
currentContextPerThread =new ConcurrentHashMap(1);
}
3、在 XmlWebApplicationContext上下文中可见如下常量,public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
而XmlWebApplicationContext正是通过调用ContextLoader类中的contextConfigLocation参数去设置文件的启动位置;
publicstatic final StringCONFIG_LOCATION_PARAM = "contextConfigLocation";
4、对于 XmlWebApplicationContext继承的父类AbstractRefreshableConfigApplicationContext中,可看到其对默认启动文件位置和自定义启动文件位置的支持。protected String[] getConfigLocations() {
return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
}