博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
简单介绍Spring的ContextLoaderListener
阅读量:7035 次
发布时间:2019-06-28

本文共 6400 字,大约阅读时间需要 21 分钟。

在开发Spring的Web项目中,通常我们都会在web.xml中配置一个Spring的核心监听器,就是把Spring的IOC容器纳入Servlet容器中,配置如下:

org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml

查看ContextLoaderListener源码如下:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {  public ContextLoaderListener() {}  public ContextLoaderListener(WebApplicationContext context) {        super(context);  }  @Override  public void contextInitialized(ServletContextEvent event) {        initWebApplicationContext(event.getServletContext());  }  @Override  public void contextDestroyed(ServletContextEvent event) {        closeWebApplicationContext(event.getServletContext());        ContextCleanupListener.cleanupAttributes(event.getServletContext());    }}

ContextLoaderListener官方源码定义是Spring的root(也就是WebApplicationContext)启动和关闭的引导监听器,当调用ContextLoaderListener的无参构造器时,就会创建一个新的ContextLoaderListener,也将会创建一个web应用上下文基于web.xml中的contextLoader和contextConfigLocation的servlet context-param参数,创建的应用上下文会被注册到ServletContext中通过WebApplicationContext里的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE这个属性。

ContextLoaderListener继承自ContextLoader并且实现了ServletContextListener接口,实现ServletContextListener作用不言而喻,就是要让Spring和Servlet容器关联起来,让Spring容器伴随着Servlet容器的启动而启动,其实这个类中最主要的一个方法就是contextInitialized(),作用就是Spring上下文初始化,里面的initWebApplicationContext()是从父类ContextLoader中继承过来的,查看源码:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {        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 {            // Store context in local instance variable, to guarantee that            // it is available on ServletContext shutdown.            if (this.context == null) {                this.context = createWebApplicationContext(servletContext);            }            if (this.context instanceof 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                    if (cwac.getParent() == null) {                        // The context instance was injected without an explicit parent ->                        // determine parent for root web application context, if any.                        ApplicationContext parent = loadParentContext(servletContext);                        cwac.setParent(parent);                    }                    configureAndRefreshWebApplicationContext(cwac, servletContext);                }            }            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;        }    }

 关于多次出现的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE这个参数,我个人理解的就是它是Servlet容器识别Spring的一个标识,如果为null,说明Spring还有没注册进Servlet容器中,

 紧接着就是创建WebApplicationContext,configureAndRefreshWebApplicationContext()这个方法最主要就是配置applicationContext.xml这个文件,

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);这句代码就是把Spring容器注册进ServletContext中。

关于WebApplicationContext这个接口:

public interface WebApplicationContext extends ApplicationContext {    String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";    String SCOPE_REQUEST = "request";    String SCOPE_SESSION = "session";    String SCOPE_GLOBAL_SESSION = "globalSession";    String SCOPE_APPLICATION = "application";    String SERVLET_CONTEXT_BEAN_NAME = "servletContext";    String CONTEXT_PARAMETERS_BEAN_NAME = "contextParameters";    String CONTEXT_ATTRIBUTES_BEAN_NAME = "contextAttributes";    ServletContext getServletContext();}

 

 WebApplicationContext继承自ApplicationContext,这个接口添加了一个getServletContext()方法,并且定义了一些root context在启动进程中必须绑定的application属性,和一般的应用上下文一样,web application contexts也是分层的,每一个应用都有一个root context,并且应用里的每个Servlet都有自己的子context,除了标准的应用上下文声明周期,WebApplicationContext实现需要探测ServletContextAware beans和调用setServletContext()方法。

WebApplicationContext里面定义了一些常用的bean作用域属性,比如request,session,globalSession,application,servletContext.

其实可以在相应的类中打断点调试,这样更能加深印象,有一点不明白的是

else if (ccl != null) {    currentContextPerThread.put(ccl, this.context);}

这段代码中ccl明明不为空,可是断点调试却不会执行,不知道哪位能解释一下。

 

转载于:https://www.cnblogs.com/liuruowang/p/5707342.html

你可能感兴趣的文章
WDS使用捕获映像制作企业自定义映像
查看>>
C++数组、指针与vector、iterator
查看>>
python将日志导入数据库代码案例2
查看>>
How to install VNC server on CentOS 6
查看>>
windows下SVN版本库迁移小结
查看>>
linux VNC 安装及配置
查看>>
编写一个UNIX文件系统
查看>>
textView跳转的activity
查看>>
PHP版本VC6和VC9、Non Thread Safe和Thread Safe的区别
查看>>
我的友情链接
查看>>
fix [Errno 13] Permission denied: '/var/log/glance/api.log'
查看>>
Cacti 0.8.8b 插件(monitor thold setting realtime)安装及邮件 短信告警
查看>>
我的友情链接
查看>>
很好的一个文字工具网址
查看>>
前辈文章摘要
查看>>
CentOS 5.5安装配置Trac1.0
查看>>
我的友情链接
查看>>
超强整理:2012年网页设计趋势
查看>>
sqoop2 五分钟实例
查看>>
线性筛素数
查看>>