Web容器在加载项目时,如Tomcat首先会加载项目的web.xml文件。
容器对于web.xml的加载过程主要流程分为:context-param >> listener >> fileter >> servlet。
Tomcat容器加载web项目的大致流程如下:
- 在启动Web项目时,容器(比如Tomcat)会读web.xml配置文件中的两个节点<listener>和<contex-param>。
- 接着容器会创建一个ServletContext(上下文),应用范围内即整个WEB项目都能使用这个上下文。一个web项目对应一个ServletContext
- 接着容器会将读取到<context-param>转化为键值对,并交给ServletContext。
- 容器创建<listener></listener>中的类实例,即创建监听(备注:listener定义的类可以是自定义的类但必须需要继承ServletContextListener)。
- 在监听的类中会有一个contextInitialized(ServletContextEvent event)初始化方法,在这个方法中可以通过event.getServletContext().getInitParameter("contextConfigLocation") 来得到context-param 设定的值。在这个类中还必须有一个contextDestroyed(ServletContextEvent event) 销毁方法.用于关闭应用前释放资源,比如说数据库连接的关闭。
- 得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早
<span style="font-size:18px;"> <context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/WEB-INF/classes/log4j.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:common-context.xml
classpath:account-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener></span>
它能够监听ServletContext对象的生命周期,实际上就是监听Web应用的生命周期。其实就是设置回调方法,在ServletContext的生命周期发生
改变的时候回调我们自己的ServletContextListener实现类中的方法。当Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,
该事件由 ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent事件的两个方法。
1、contextInitialized(ServletContextEvent sce):当Servlet容器启动Web应用时调用该方法。在调用完该方法之后,容器再对Filter初始化,
并且对那些在Web应用启动时就需要被初始化的Servlet进行初始化。
2、contextDestroyed(ServletContextEvent sce):当Servlet容器终止Web应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet
和Filter过滤器。
由于Springweb项目配置ContextLoaderListener 监听器,且该监听器实现接口ServletContextListener,所以Servlet容器启动的时候就会回调
方法contextInitialized。查看ContextLoaderListener 的contextInitialized实现方法:
<span style="font-size:18px;"> public void contextInitialized(ServletContextEvent event) {
// 以及抛弃,返回null
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}</span>
实际是委托当前contextLoader去初始化WebApplicationContext,而WebApplicationContext就是Spring MVC项目中的IOC容器。称之为
The root WebApplicationContext,根上下文,而后面初始化的DispatcherServlet的MVC容器是该ROOT容器的子上下文。
查看参数ServletContextEvent ,是在Servlet容器启动触发的事件,可以通过该事件获取当前的ServletContext容器信息。可以调试发现
当前的ServletContext其实是子类ApplicationContextFacade。
可以调试查看当前的Servlet中的属性信息:
其中parameters,其实就是web.xml中的<context-param>属性信息,使用的是并发hashmap存储
实际进入initWebApplicationContext后 创建具体的IOC容器。调试发现时XmlWebApplicationContext。
<span style="font-size:18px;">this.context = createWebApplicationContext(servletContext);</span>
具体方法内执行如下:
<span style="font-size:18px;">public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
// servletContext中是否以及记录IOC根上下文
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
// context记录IOC容器,即XmlWebApplicationContext
if (this.context == null) {
// 创建XmlWebApplicationContext
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
// 转成父类ConfigurableWebApplicationContext
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
// IOC的双亲容器
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
// 创建双亲IOC容器,默认null
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
// 刷新容器,解析配置信息
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 设置ServletContext的属性根上下文为 新建IOC容器的
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
...
return this.context;
}
...
}</span>
查看configureAndRefreshWebApplicationContext方法:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
// Servlet <= 2.4: resort to name specified in web.xml, if any.
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getServletContextName()));
}
else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
}
wac.setServletContext(sc);
// 获取配置参数信息,CONFIG_LOCATION_PARAM 为contextConfigLocation
// 也就是在web.xml中配置的初始化参数
String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (initParameter != null) {
// 设置配置文件
wac.setConfigLocation(initParameter);
}
customizeContext(sc, wac);
// 刷新加载bean定义信息
wac.refresh();
}
XMLWebApplicationContext源码中可以看到:
<span style="font-size:18px;">public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
/** Default config location for the root context */
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
/** Default prefix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
/** Default suffix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";</span>
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
String[] configLocations = getConfigLocations();
if (configLocations != null) {
for (String configLocation : configLocations) {
reader.loadBeanDefinitions(configLocation);
}
}
}
在XmlWebApplicationContext的初始化过程中,Web容器中的IOC容器就建立起来了。