当前位置: 代码迷 >> Web前端 >> Spring起动<三>――XmlWebApplicationContext
  详细解决方案

Spring起动<三>――XmlWebApplicationContext

热度:92   发布时间:2012-10-08 19:54:56.0
Spring启动<三>――XmlWebApplicationContext

??? 在上一篇中,我们已经看过了XmlWebApplicationContext的实例化过程。回头看看《Spring启动<一>》中org.springframework.web.context.ContextLoader中的方法protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent)的剩下部分代码,代码如下:

ServletContext sc = ...;
ConfigurableWebApplicationContext wac = ...;
//wac实例化之后的代码
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(null);
wac.setServletContext(sc);
wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));
customizeContext(sc, wac);
wac.refresh();

??? 这些代码可以分为两个部分来看,第一部分是if...else...语句中的内容,这一部分根据当前Servlet容器支持的Servlet版本来取一个值,从而调用wac.setId(String id)。查看源代码可以知道,setId方法的是XmlWebApplicationContext的一个祖先类org.springframework.context.support.AbstractApplicationContext中提供的。该类的注释是“Set the unique id of this application context.Default is the object id of the context instance, or the name of the context bean if the context is itself defined as a bean.”

??? 第二部分中,wac.setParent(null),wac.setServletContext(sc), wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM))均只是简单的赋值操作,尤其setConfigLocation是将spring配置文件的路径传入进去了。customizeContext(sc, wac)调用的是org.springframework.web.context.ContextLoader中的对应方法。该方法默认是个空方法。

??? 走到最后一步wac.refresh().通过查找发现,这个方法的实现在XmlWebApplicationContext的一个祖先类org.springframework.context.support.AbstractApplicationContext中。下一篇我们就要看看在这一步操作中,系统做了哪些操作。

?

?

?

?

  相关解决方案