Spring MVC DispatcherServlet的啟動以及初始化
阿新 • • 發佈:2019-01-05
protected WebApplicationContext initWebApplicationContext() { //這裡通過WebApplicationContextUtils工具類來獲取根web應用上下文,這個上下文就是之前提到的全域性應用根上下文,儲存在ServletContext中,這個根上下文將作為當前mvc servlet上下文的雙親上下文。 WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext wac = null; if (this.webApplicationContext != null) { // A context instance was injected at construction time -> use it wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac; 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 -> set // the root application context (if any; may be null) as the parent cwac.setParent(rootContext); } configureAndRefreshWebApplicationContext(cwac); } } } if (wac == null) { // No context instance was injected at construction time -> see if one // has been registered in the servlet context. If one exists, it is assumed // that the parent context (if any) has already been set and that the // user has performed any initialization such as setting the context id wac = findWebApplicationContext(); } if (wac == null) { //這裡真正建立需要與該Servlet相關聯的WebApplicationContext // No context instance is defined for this servlet -> create a local one wac = createWebApplicationContext(rootContext); } if (!this.refreshEventReceived) { // Either the context is not a ConfigurableApplicationContext with refresh // support or the context injected at construction time had already been // refreshed -> trigger initial onRefresh manually here. //這裡,ioc容器已經建立初始化完成,執行onRefresh(wac)進一步初始化MVC其他模組,後面說明 onRefresh(wac); } if (this.publishContext) { //這裡將當前建立的上下文儲存到ServletContext中,attrName 是與當前servlet名相關聯,保證唯一性 // Publish the context as a servlet context attribute. String attrName = getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); if (this.logger.isDebugEnabled()) { this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() + "' as ServletContext attribute with name [" + attrName + "]"); } } return wac; }