一、作用:为根应用上下文执行初始化工作
二、加载默认的WebApplicationContext
在ContextLoader.class同级目录下面有一个文件:ContextLoader.properties,该文件里面声明了默认的WebApplicationContext实现类:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
这就是我们常用的XmlWebApplicationContext,如果我们想自己声明WebApplicationContext实现类,那么可以通过使用context-param的参数配置来实现。当然ContextLoader.properties我们是没有办法进行定制的。
三、初始化:
1、首先检查ServletContext里面是否有属性名为:org.springframework.web.context.WebApplicationContext.ROOT的属性,如果有,则抛出异常
2、createWebApplicationContext
2.1、检查web.xml里面是否有如下配置的初始化参数,如果有,则直接使用ClassUtils.forName来获取WebApplicationContext对象,否则就使用ContextLoader.properties定义的WebApplicationContext类

2.2、如果我们自己实现WebApplicationContext,那么必须实现ConfigurableWebApplicationContext接口,因为这个时候,spring会将WebApplicationContext强转成ConfigurableWebApplicationContext
3、loadParentContext (正常情况下,是没有此步骤的)
检查web.xml里面是否有属性为parentContextKey的初始化参数,

如果有,再看web.xml里面是否有属性为locatorFactorySelector的初始化参数,如果没有此参数,则使用默认值:classpath*:beanRefContext.xml

然后加载ParentContext,并设置当前的ParentContext
4、configureAndRefreshWebApplicationContext(这才是重点)
5、把初始化好的ApplicationContext设置到ServletContext的属性名为:org.springframework.web.context.WebApplicationContext.ROOT的值
网友评论