SpringMVC(二)ContextLoaderListenner
来源:互联网 发布:数据库原理与应用样卷 编辑:程序博客网 时间:2024/06/03 20:08
对于SpringMVC功能实现的分析,我们首先从web.xml开始,在web.xml文件中我们首先配置的就是ContextLoaderListener,那么它所提供了功能有哪些又是如何实现的?
当使用编程方式的时候我们可以将Spring配置传入到Spring容器中,如:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
但是在web下,我们需要更多的是与Web环境相互结合,通常的办法是将路径以context-param的方式注册并使用ContextLoaderListener进行监听读取。
ContextLoaderListener的作用是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法,使用ServletContextListener接口,开发者能够在为客户端请求提供服务之前向ServletContext中添加任意的对象。这个对象在ServletContext启动的时候被初始化,然后再ServletContext整个运行期间都是可见的。
每一个web应用都有一个ServletContext与之相关联。ServletContext对象在应用启动时被创建,在应用关闭的时候被销毁。ServletContext在全局范围内有效,类似于应用中的一个全局变量。
在ServletContextListener中的核心逻辑便是初始化WebApplicationContext实例并存在至ServletContext中。
1.ServletContextListener的使用
正式分析代码前我们同样还是先了解下ServletContextListener的使用。
(1)创建自定义ServletContextListener.
首先我们创建ServletContextListener,目标是在系统启动时添加自定义属性,以便于在全局范围内可以随时调用。系统启动的时候会调用ServletContextListener实现类的contextInitialized方法,所以需要在这个方法中实现我们初始化的逻辑。
public class MyDataContextListener implements ServletContextListener{ private ServletContext context = null; public MyDataContextListener(){ } //该方法在ServletContext启动之后调用,并准备好处理客户端请求 public void contextInitialized(ServletContextEvent event){ this.context = event.getServletContext(); //通过你可以实现自己的记录并记录在属性中 context = setAttribute("myData","this is myData"); } //这个方法在ServletContext将要关闭的时候调用 public void contextDestroyed(ServletContextEvent event){ this.context = null; }}
(2)注册监听器。
在web.xml中需要注册自定义的监听器
<listener>com.test.MydataContextListener</listener>(3)测试
一旦在web应用启动的时候,我们就能在任意的Servlet或者JSP中通过下面的方式获取我们初始化的参数,如下:
String myData = (String)getServletContext().getAttribute("myData");
2.2Spring中的ContextLoaderListener
分析了ServletContextListener的使用方式之后再来分析Spring中的ContextLoaderListener的实现就容易理解多了,虽然ContextLoaderListener实现的逻辑要复杂的多,但是大致的套路还是差不多的。
ServletContext启动之后会调用ServletContextListener的contextInitialized方法,那么就我们从这个函数开始分析:
public void contextInitialized(ServletContextEvent event) {this.contextLoader = createContextLoader();if (this.contextLoader == null) {this.contextLoader = this;} //初始化WebApplicationContextthis.contextLoader.initWebApplicationContext(event.getServletContext());}
这里涉及到了一个常用类WebApplicationContext:在web应用中,我们会用到WebApplicationContext,WebApplicationContext继承自ApplicationContext,在ApplicationContext的基础上又追加了一些特定于web的操作及属性,非常类似于我们通过变成方式使用Spring时使用的ClassPathXmlApplicationContext类提供的功能。继续跟踪代码:
/* *initWebApplicationContext函数主要是体现了创建WebApplicationContext实例的一个功能架构,从函数中我们看到了初始化的大致步骤 * */ public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { //WebApplicationContext存在性的验证。 //在配置中值允许声明一次ServletContextListener,多次声明会扰乱Spring的执行逻辑,所以这里首先做的就是对此验证 //在Spring中如果创建WebApplicationContext实例会 记录在ServletContext中以方便全局调用,而使用的key就是WebApplicationContext. //ROOT_WEB_APPLICSTION_CONTEXT_ATTRIBUTE,所以验证方式就是查看ServletContext实例中是否有对应的key的属性。 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!");}Log logger = LogFactory.getLog(ContextLoader.class);servletContext.log("Initializing Spring root WebApplicationContext");if (logger.isInfoEnabled()) {logger.info("Root WebApplicationContext: initialization started");}long startTime = System.currentTimeMillis();try {// Determine parent for root web application context, if any.ApplicationContext parent = loadParentContext(servletContext);// Store context in local instance variable, to guarantee that// it is available on ServletContext shutdown. //创建WebApplicationContext实例。 this.context = createWebApplicationContext(servletContext, parent);servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);ClassLoader ccl = Thread.currentThread().getContextClassLoader();if (ccl == ContextLoader.class.getClassLoader()) {currentContext = this.context;}else if (ccl != null) {currentContextPerThread.put(ccl, this.context);}if (logger.isDebugEnabled()) {logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");}if (logger.isInfoEnabled()) {long elapsedTime = System.currentTimeMillis() - startTime;logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");}return this.context;}catch (RuntimeException ex) {logger.error("Context initialization failed", ex);servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);throw ex;}catch (Error err) {logger.error("Context initialization failed", err);servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);throw err;}}上面这段代码最重要的就是
createWebApplicationContext这个方法创建webApplicationContext实例。代码如下:
protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent) {Class<?> contextClass = determineContextClass(sc);if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {throw new ApplicationContextException("Custom context class [" + contextClass.getName() +"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");}ConfigurableWebApplicationContext wac =(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);// Assign the best possible id value.if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {// Servlet <= 2.4: resort to name specified in web.xml, if any.String servletContextName = sc.getServletContextName();wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(servletContextName));}else {// Servlet 2.5's getContextPath available!try {String contextPath = (String) ServletContext.class.getMethod("getContextPath").invoke(sc);wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(contextPath));}catch (Exception ex) {throw new IllegalStateException("Failed to invoke Servlet 2.5 getContextPath method", ex);}}wac.setParent(parent);wac.setServletContext(sc);wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));customizeContext(sc, wac);wac.refresh();return wac;}
其中,在ContextLoader类中有这样的静态代码块:
static {// Load default strategy implementations from properties file.// This is currently strictly internal and not meant to be customized// by application developers.try {ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);}catch (IOException ex) {throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());}}
根据以上静态代码块我们推断在当前ContextLoader类同目录下必然存在属性文件ContextLoader.properties,c产看后果然存在,代码如下:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
综合以上代码分析,在初始化的过程中,程序首先会读取ContextLoader类同目录下的属性文件ContextLoader.properties。并根据其中配置提取将要实现WebApplicationContext接口的实现类,并根据这个实现类通过反射的方式进行实例的创建
(3)将实例记录在servletContext中
customizeContext(sc, wac);
(4)映射当前的类加载器与创建的实例到全局变量currentContextPerhread中。
else if (ccl != null) {currentContextPerThread.put(ccl, this.context);}
- SpringMVC(二)ContextLoaderListenner
- springMVC二
- springMVC(二)
- SpringMvc(二)
- SpringMvc(二)配置SpringMvc
- springMVC入门(二)
- SpringMVC学习笔记二
- springMVC学习(二)
- SpringMVC学习总结(二)
- SpringMVC-基础知识点(二)
- SpringMvc 深入讲解 二
- SpringMVC学习(二)
- 二、SpringMvc 进阶
- 二:springmvc Controller
- SpringMVC(二)
- SpringMVC(二) 流程控制
- springMVC笔记(二)
- springMVC实例(二)
- java Jedis连接池的使用
- 李开复微博数据分析--微博爬虫、数据挖掘、数据可视化(持续更新)
- clang: error: linker command failed with exit code 1 (use -v to see invocation)解决办法
- maven学习(下)利用Profile构建不同环境的部署包
- ng2 DI
- SpringMVC(二)ContextLoaderListenner
- 修改caffe输出multilabel,并自己训练完成了一个神经网络,初步达到目标检测的效果
- postgresql时间函数j2date
- 安卓学习笔记---Fragment 里面加webview 监听onback事件(WebView的返回以及整个退出事件)
- Java远程访问SQL Server 2008R2数据库
- PAT-1001
- Tomcat7通过redis 来进行session复制的设置过程(jcoleman/tomcat-redis-session-manager)
- 【杭电oj】2089 - 不要62(打表)
- poj2585 Window Pains (裸拓扑排序)