您的位置:首页 > 移动开发 > WebAPP

Spring启动<三>——XmlWebApplicationContext

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

Java代码


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中。下一篇我们就要看看在这一步操作中,系统做了哪些操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐