Spring(MVC)啟動(dòng)淺析與父子Context

現(xiàn)在在Java web 的世界中,很多都用spring的,因?yàn)樗母叨冉怦?,使得開發(fā)人員能夠快速構(gòu)建出高可用和高擴(kuò)展的應(yīng)用。我們看下spring在web項(xiàng)目中的啟動(dòng)過程和上下文的使用情況。web 應(yīng)用啟動(dòng)過程可以參考上一篇文章。http://www.itdecent.cn/p/a9babadb5f4b
我一般都用xml或者注解的方式使用spring,先說(shuō)下xml的

1、xml based configuration

在XML based configuration的項(xiàng)目中,web.xml大致如下:

<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

</web-app>

ContextLoaderListener 如下:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    public ContextLoaderListener() {
    }

    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }

    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());
    }

    public void contextDestroyed(ServletContextEvent event) {
        this.closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
}

在應(yīng)用啟動(dòng)的時(shí)候,會(huì)調(diào)用contextInitialized,里面調(diào)用ContextLoader 的initWebApplicationContext 方法(servlet context 已經(jīng)由web容器創(chuàng)建好了),方法中會(huì)創(chuàng)建 WebApplicationContext 并把它注冊(cè)到servlet context中:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
WebApplicationContext 熟悉吧?xml用的XmlWebApplicationContext、groovy用的GroovyWebApplicationContext、基于注解的AnnotationConfigWebApplicationContext 都是它的實(shí)現(xiàn)類。它就是作為IOC容器的上下文,也是root context。

看下initWebApplicationContext方法的兩個(gè)關(guān)鍵點(diǎn):

this.context = this.createWebApplicationContext(servletContext);//創(chuàng)建WebApplicationContext對(duì)象
...
if(this.context instanceof ConfigurableWebApplicationContext) {
      ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)this.context;
      if(!cwac.isActive()) {
          if(cwac.getParent() == null) {
                   ApplicationContext parent = this.loadParentContext(servletContext);
                         cwac.setParent(parent);//將web application context 的父容器設(shè)置為servletContext
           }
           this.configureAndRefreshWebApplicationContext(cwac, servletContext);
      }
}

root context初始化完了以后,按照定義的順序開始加載初始化servlet。這里是DispatcherServlet。DispatcherServlet在初始化的時(shí)候,會(huì)創(chuàng)建自己的IOC context(servlet application context),并且從servlet context中取出屬性名為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 的context,也就是root context,并根據(jù)創(chuàng)建出來(lái)的context創(chuàng)建DispatcherServlet,注冊(cè)過濾器,最后將DispatcherServlet加入到servlet context(root context)中。servletApplicationContext 就作為WebApplicationContext的子容器了。這個(gè)不太直觀,我們看下基于注解的配置的代碼就很清楚了。

2、annotation based configuration

web application context:

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { MyWebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

web mvc context:

class MyWebConfig extends WebMvcConfigurationSupport {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ...
     }
}

我們看看AbstractAnnotationConfigDispatcherServletInitializer:

public abstract class AbstractAnnotationConfigDispatcherServletInitializer extends AbstractDispatcherServletInitializer {
    public AbstractAnnotationConfigDispatcherServletInitializer() {
    }

    @Nullable
    protected WebApplicationContext createRootApplicationContext() {
        Class<?>[] configClasses = this.getRootConfigClasses();
        if(!ObjectUtils.isEmpty(configClasses)) {
            AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
            rootAppContext.register(configClasses);
            return rootAppContext;
        } else {
            return null;
        }
    }

    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
        Class<?>[] configClasses = this.getServletConfigClasses();
        if(!ObjectUtils.isEmpty(configClasses)) {
            servletAppContext.register(configClasses);
        }

        return servletAppContext;
    }

    @Nullable
    protected abstract Class<?>[] getRootConfigClasses();

    @Nullable
    protected abstract Class<?>[] getServletConfigClasses();
}

主要就是創(chuàng)建rootApplicationContext 和 servletApplicationContext,也就是兩個(gè)父子容器了。
再來(lái)看看AbstractDispatcherServletInitializer,主要代碼如下:

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

    protected void registerDispatcherServlet(ServletContext servletContext) {
        String servletName = this.getServletName();
        WebApplicationContext servletAppContext = this.createServletApplicationContext();
        FrameworkServlet dispatcherServlet = this.createDispatcherServlet(servletAppContext);
        dispatcherServlet.setContextInitializers(this.getServletApplicationContextInitializers());
        Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping(this.getServletMappings());
        registration.setAsyncSupported(this.isAsyncSupported());
        Filter[] filters = this.getServletFilters();
        if(!ObjectUtils.isEmpty(filters)) {
            Filter[] var7 = filters;
            int var8 = filters.length;

            for(int var9 = 0; var9 < var8; ++var9) {
                Filter filter = var7[var9];
                this.registerServletFilter(servletContext, filter);
            }
        }

        this.customizeRegistration(registration);
    }

    protected String getServletName() {
        return "dispatcher";
    }

    protected abstract WebApplicationContext createServletApplicationContext();

    protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
        return new DispatcherServlet(servletAppContext);
    }

看到代碼了,就是那么實(shí)現(xiàn)的。哈!

父子容器(父:WebApplicationContext,子:ServletApplicationContext),在子容器中可以訪問父容器中的bean,但是,父容器中卻不能夠訪問子容器中的bean,這個(gè)是很自然的事情。。父容器中的bean主要是 DAO、service、repository,也就是業(yè)務(wù)邏輯層和數(shù)據(jù)持久化層;子容器中主要就是controller,也就是ACTION相關(guān)的東西。這個(gè)是很自然的事情,mvc嘛,子容器訪問父容器中的bean,不正是mvc中的c調(diào)用m?

一個(gè)不標(biāo)準(zhǔn)的時(shí)序和調(diào)用圖如下:


Jin.png

這種采用父子容器的方式是很正規(guī),中規(guī)中矩的方式,其實(shí)也可以直接都在同一個(gè)context中,不過不建議這樣做。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容