一,容器初始化
1,在web.xml中配置ContextLoaderListener
这个监听器实现了ServletContextListener,这个接口有2个方法。
public void contextInitialized ( ServletContextEvent sce );
public void contextDestroyed ( ServletContextEvent sce );
参数ServletContextEvent能直接获取servletContext也就是java web容器的上下文。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
从而也就能获取到context-config的数据。
监听器的父类ContextLoader首先执行静态代码块。
(复习下类的初始化顺序:
父类静态代码块,实例变量
子类静态代码块,实例变量
父类非静态代码块,实例变量
子类非静态代码块,实例变量
父类构造方法
子类构造方法
)
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
//DEFAULT_STRATEGIES_PATH = ContextLoader.properties;
//class path resource [org/springframework/web/context/ContextLoader.properties]
//在ContextLoader.properties中只有一对键值对:
//org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
//将ContextLoader.properties中的值,复制到defaultStrategies这个Properties对象中。(默认策略)
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
我认为
ContextLoaderListener调用的是无参构造方法.
然后是执行contextInitialized 方法,调用父类的
initWebApplicationContext方法,将ServletContext作为参数传递.
那么,
initWebApplicationContext(ServletContext)这个方法做了些什么呢?
/**
* Initialize Spring's web application context for the given servlet context,
使用servletContext初始化spring web application context
* using the application context provided at construction time, or creating a new one
* according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
* "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
* @param servletContext current servlet context
* @return the new WebApplicationContext
* @see #ContextLoader(WebApplicationContext)
* @see #CONTEXT_CLASS_PARAM
* @see #CONFIG_LOCATION_PARAM
*/
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//检测servletContext的属性中是否存在spring的根上下文属性
//如果存在则是错误的,因为表明已经有一个根上下文已经启动,再启动会冲突,所以避免重复启动!
//不可以在web.xml中配置2个及多个ContextLoaderListener.