二十四、spring mvc之上下文加載

由上節(jié)二十三、spring mvc之簡單使用,SpringServletContainerInitializer找到所有的WebApplicationInitializer后,會調(diào)用它們的onStartup方法,這節(jié)我們看下AbstractAnnotationConfigDispatcherServletInitializer的onStartup執(zhí)行邏輯胁出。
AbstractAnnotationConfigDispatcherServletInitializer類圖如下:

AbstractAnnotationConfigDispatcherServletInitializer

onStartup方法在AbstractAnnotationConfigDispatcherServletInitializer父類AbstractDispatcherServletInitializer實(shí)現(xiàn):

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    registerDispatcherServlet(servletContext);
}

AbstractDispatcherServletInitializer又調(diào)用它的父類AbstractContextLoaderInitializer的onStartup方法。

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    registerContextLoaderListener(servletContext);
}

兩個onStartup方法分別調(diào)用了registerDispatcherServlet和registerContextLoaderListener方法段审,從方法名上我們能夠猜出他們的功能全蝶,分別是注冊DispatcherServlet和ContextLoaderListener。接下來我們具體分析這兩個方法寺枉。

registerContextLoaderListener方法

protected void registerContextLoaderListener(ServletContext servletContext) {
    //1. 創(chuàng)建Spring上下文
    WebApplicationContext rootAppContext = createRootApplicationContext();
    if (rootAppContext != null) {
        //2. 創(chuàng)建ContextLoaderListener監(jiān)聽器
        ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
        listener.setContextInitializers(getRootApplicationContextInitializers());
        servletContext.addListener(listener);
    }
    else {
        logger.debug("No ContextLoaderListener registered, as " +
                "createRootApplicationContext() did not return an application context");
    }
}

registerContextLoaderListener方法執(zhí)行邏輯如下:

  1. 創(chuàng)建Spring上下文抑淫,上下文的創(chuàng)建交給子類AbstractAnnotationConfigDispatcherServletInitializer實(shí)現(xiàn)。
@Override
protected WebApplicationContext createRootApplicationContext() {
    //1. 得到配置類路徑姥闪,這個方法給使用者重寫的
    Class<?>[] configClasses = getRootConfigClasses();
    if (!ObjectUtils.isEmpty(configClasses)) {
        //2. 創(chuàng)建AnnotationConfigWebApplicationContext對象
        AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
        rootAppContext.register(configClasses);
        return rootAppContext;
    }
    else {
        return null;
    }
}
  1. 創(chuàng)建ContextLoaderListener監(jiān)聽器,并把監(jiān)聽器添加的servlet上下文中始苇。

初始化Spring上下文

ContextLoaderListener實(shí)現(xiàn)ServletContextListener,在servlet容器啟動的時候就會調(diào)用它的contextInitialized方法筐喳。我們看下它的實(shí)現(xiàn)催式。

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的contextInitialized又調(diào)用父類ContextLoader的initWebApplicationContext方法。

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    //1. spring上下文是否已經(jīng)加載過
    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);
                }
                //2. 調(diào)用refresh加載Spring上下文
                configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
        }
        //3. 設(shè)置spring上下文已經(jīng)加載完成
        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;
    }
}

initWebApplicationContext方法代碼很長避归,業(yè)務(wù)邏輯不難荣月,主要是做各種判斷。邏輯如下:

  1. 判斷Spring上下文是否已經(jīng)加載過梳毙,保證只加載一次哺窄。
  2. 加載Spring上下文,調(diào)用的configureAndRefreshWebApplicationContext账锹,調(diào)用的是我們很熟悉的refresh方法萌业。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
        // The application context id is still set to its original default value
        // -> assign a more useful id based on available information
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);
        }
        else {
            // Generate default id...
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
                    ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }

    wac.setServletContext(sc);
    String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
    if (configLocationParam != null) {
        wac.setConfigLocation(configLocationParam);
    }

    // The wac environment's #initPropertySources will be called in any case when the context
    // is refreshed; do it eagerly here to ensure servlet property sources are in place for
    // use in any post-processing or initialization that occurs below prior to #refresh
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }

    customizeContext(sc, wac);
    //刷新
    wac.refresh();
}
  1. 設(shè)置spring上下文已經(jīng)加載完成

registerDispatcherServlet

protected void registerDispatcherServlet(ServletContext servletContext) {
    //1. 得到servlet名字,默認(rèn)是dispatcher
    String servletName = getServletName();
    Assert.hasLength(servletName, "getServletName() must not return empty or null");

    //2. 創(chuàng)建Servlet上下文
    WebApplicationContext servletAppContext = createServletApplicationContext();
    Assert.notNull(servletAppContext,
            "createServletApplicationContext() did not return an application " +
            "context for servlet [" + servletName + "]");
    //3. 創(chuàng)建dispatcherServlet
    FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
    dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());

    //4. 注冊dispatcherServlet
    ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
    Assert.notNull(registration,
            "Failed to register servlet with name '" + servletName + "'." +
            "Check if there is another servlet registered under the same name.");

    registration.setLoadOnStartup(1);
    registration.addMapping(getServletMappings());
    registration.setAsyncSupported(isAsyncSupported());

    //5. 注冊過濾器奸柬,這些過濾器都是針對dispatcherServlet咽白,所以不需要配置Mapping
    Filter[] filters = getServletFilters();
    if (!ObjectUtils.isEmpty(filters)) {
        for (Filter filter : filters) {
            registerServletFilter(servletContext, filter);
        }
    }

    customizeRegistration(registration);
}

registerDispatcherServlet方法的邏輯也很簡單,命名好的重要性。

  1. 得到servlet名字鸟缕,默認(rèn)是dispatcher
  2. 創(chuàng)建Servlet上下文,還是交給子類AbstractAnnotationConfigDispatcherServletInitializer完成.
@Override
protected WebApplicationContext createServletApplicationContext() {
    //和Spring上下問使用的是同一種上下文
    AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
    //子類重寫
    Class<?>[] configClasses = getServletConfigClasses();
    if (!ObjectUtils.isEmpty(configClasses)) {
        servletAppContext.register(configClasses);
    }
    return servletAppContext;
}
  1. 創(chuàng)建dispatcherServlet
  2. 注冊dispatcherServlet
  3. 注冊過濾器,獲取過濾器由子類重寫,這些過濾器主要是針對dispatcherServlet排抬,對其他的Servlet不生效懂从。

初始化Servlet上下文

registerDispatcherServlet方法中只是創(chuàng)建了Servlet上下文,并沒有加載上下文蹲蒲。那么加載的動作在哪做的呢番甩?
DispatcherServlet的類圖如下:


DispatcherServlet

DispatcherServlet實(shí)現(xiàn)自HttpServlet,在Servlet容器加載的時候届搁,會調(diào)用Servlet的init方法缘薛。DispatcherServlet的init方法在父類HttpServletBean中.

@Override
public final void init() throws ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("Initializing servlet '" + getServletName() + "'");
    }

    // Set bean properties from init parameters.
    //1. 設(shè)置初始化參數(shù)
    PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
    if (!pvs.isEmpty()) {
        try {
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
            initBeanWrapper(bw);
            bw.setPropertyValues(pvs, true);
        }
        catch (BeansException ex) {
            if (logger.isErrorEnabled()) {
                logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
            }
            throw ex;
        }
    }

    // Let subclasses do whatever initialization they like.
    //2. 初始Servlet,由子類實(shí)現(xiàn)
    initServletBean();

    if (logger.isDebugEnabled()) {
        logger.debug("Servlet '" + getServletName() + "' configured successfully");
    }
}

init方法做了兩件事:

  1. 設(shè)置初始化參數(shù)
  2. 初始Servlet,子類FrameworkServlet實(shí)現(xiàn)了這個方法
@Override
protected final void initServletBean() throws ServletException {
    getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
    if (this.logger.isInfoEnabled()) {
        this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
    }
    long startTime = System.currentTimeMillis();

    try {
        //初始化Servlet上下文
        this.webApplicationContext = initWebApplicationContext();
        initFrameworkServlet();
    }
    catch (ServletException ex) {
        this.logger.error("Context initialization failed", ex);
        throw ex;
    }
    catch (RuntimeException ex) {
        this.logger.error("Context initialization failed", ex);
        throw ex;
    }

    if (this.logger.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
                elapsedTime + " ms");
    }
}

上面方法這么長的代碼窍育,只做了一件事,初始化Servlet上下文宴胧。

protected WebApplicationContext initWebApplicationContext() {
    //1. 得到Spring上下文
    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
                    //2. 設(shè)置Spring上下文作為當(dāng)前父上下文
                    cwac.setParent(rootContext);
                }
                //調(diào)用refresh()
                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) {
        // 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.
        onRefresh(wac);
    }

    if (this.publishContext) {
        // 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;
}

初始化Servlet上下文流程如下:

  1. 得到Spring上下文漱抓,把Spring上下文設(shè)置成Servlet上下文的parent。
  2. 調(diào)用refresh方法加載上下文恕齐。這里和Spring上下文的邏輯差不多乞娄,就不貼代碼了。

疑惑

為什么Servlet上下文能夠獲得到Spring上下文中的bean显歧。我在DefaultListableBeanFactory的getBean中找到答案:

@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
    //1. 從自己的容器中獲取bean
    NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args);
    if (namedBean != null) {
        return namedBean.getBeanInstance();
    }
    //2. 如果自己容器中沒有仪或,則嘗試從父類容器中獲取
    BeanFactory parent = getParentBeanFactory();
    if (parent != null) {
        return parent.getBean(requiredType, args);
    }
    throw new NoSuchBeanDefinitionException(requiredType);
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市士骤,隨后出現(xiàn)的幾起案子范删,更是在濱河造成了極大的恐慌,老刑警劉巖拷肌,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件到旦,死亡現(xiàn)場離奇詭異,居然都是意外死亡廓块,警方通過查閱死者的電腦和手機(jī)厢绝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來带猴,“玉大人昔汉,你說我怎么就攤上這事∷┣澹” “怎么了靶病?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長口予。 經(jīng)常有香客問我娄周,道長,這世上最難降的妖魔是什么沪停? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任煤辨,我火速辦了婚禮,結(jié)果婚禮上木张,老公的妹妹穿的比我還像新娘众辨。我一直安慰自己,他們只是感情好舷礼,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布鹃彻。 她就那樣靜靜地躺著,像睡著了一般妻献。 火紅的嫁衣襯著肌膚如雪蛛株。 梳的紋絲不亂的頭發(fā)上团赁,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天,我揣著相機(jī)與錄音谨履,去河邊找鬼欢摄。 笑死,一個胖子當(dāng)著我的面吹牛屉符,可吹牛的內(nèi)容都是我干的剧浸。 我是一名探鬼主播,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼矗钟,長吁一口氣:“原來是場噩夢啊……” “哼唆香!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起吨艇,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤躬它,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后东涡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體冯吓,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年疮跑,在試婚紗的時候發(fā)現(xiàn)自己被綠了组贺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡祖娘,死狀恐怖失尖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情渐苏,我是刑警寧澤掀潮,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站琼富,受9級特大地震影響仪吧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鞠眉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一薯鼠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧械蹋,春花似錦出皇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽涩金。三九已至谱醇,卻和暖如春暇仲,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背副渴。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工奈附, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人煮剧。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓斥滤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親勉盅。 傳聞我的和親對象是個殘疾皇子佑颇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容