对于熟悉Spring MVC功能,首先应从web.xml 开始,在web.xml 文件中我们需要配置一个监听器 ContextLoaderListener,如下。
<!-- 加载spring上下文信息,最主要的功能是解析applicationContext.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置applicationContext.xml的位置路径,让ContextLoaderListener进行加载该配置文件,并解析 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml
</param-value>
</context-param>
ContextLoaderListener有什么用?提供什么功能呢?我们下面通过源码分析下。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
//web 容器启动时执行
@Override
public void contextInitialized(ServletContextEvent event) {
//初始化WebApplicationContext对象
initWebApplicationContext(event.getServletContext());
}
//web容器销毁时执行
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
ContextLoaderListener 实现了ServletContextListener 接口。 ServletContextListener 接口我们知道是web容器创建的时候开始执行contextInitialized() 方法,web容器销毁时执行contextDestroyed() 方法。那我们就从contextInitialized() 方法开始分析。
public void contextInitialized(ServletContextEvent event) {
//初始化WebApplicationContext对象
initWebApplicationContext(event.getServletContext());
}
从当前类的路径下查找 ContextLoader.properties 并加载文件中的键值存储到 defaultStrategies中。
# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
通过WebApplicationContext全类名获取它的实现类是XmlWebApplicationContext。
通过代码分析ContextLoaderListener的作用就是启动Web容器的时候,初始化WebApplicationContext实例,并存放到ServletContext中。
ContextLoaderListener实现了ServletContextListener接口,在Web容器启动的时会默认执行它的contextInitialized() 方法,然后获取WebApplicationContext的实现类 XmlWebApplicationContext,并实例化后存放到ServletContext中,通过XmlWebApplicationContext类进行加载、解析applicationContext.xml 配置文件。ServletContext在整个Web容器范围内都有效,都可以获取得到。
通过代码可以大概了解到就是读取web.xml中配置的applicationContext.xml ,然后加载解析Bean信息。