Spring MVC源碼解讀一

閱讀前提:
1灌闺、理解IOC的一些概念萤衰,以及在Spring中的實(shí)現(xiàn)(上下文堕义,BeanFactory,BeanDefinition等等)
2腻菇、理解Web的基礎(chǔ)知識(Servlet)
3胳螟、理解MVC的基礎(chǔ)知識(Model/View/Controller)

spring mvc的配置解析:

一、需要在web.xml中配置DispatchServlet

 <!-- Spring MVC 配置 -->
    <servlet>
        <servlet-name>spring-sample</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-sample</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

<!-- Spring bean配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 指定Spring Bean的配置文件所在目錄筹吐。默認(rèn)配置在WEB-INF目錄下 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

1.servlet節(jié)點(diǎn)描述的是servlet對象糖耸,這里是spring mvc的DispatcherServlet,servlet的名稱為spring-sample

2.servlet-mapping節(jié)點(diǎn)描述的是url映射丘薛,這里定義了對于任何/*的請求都走名稱為spring-sample的servlet去處理

3.listener節(jié)點(diǎn)描述的spring mvc的啟動類嘉竟,ContextLoaderListener被定義為一個監(jiān)聽器,負(fù)責(zé)完成IoC容器在web環(huán)境中的啟動

4.context-param節(jié)點(diǎn)描述的是spring的bean配置文件

5.servlet的load-on-startup作用:
關(guān)于load-on-startup的官方描述
Servlet specification: The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value
load-on-startup指明當(dāng)web應(yīng)用啟動的時候洋侨,初始化servlet(調(diào)用init()方法)舍扰,
1)當(dāng)值為0或者大于0時,表示容器在應(yīng)用啟動時就加載并初始化這個servlet希坚;
2)當(dāng)值小于0或者沒有指定時边苹,則表示容器在該servlet被選擇時才會去加載;
3)值越小裁僧,該servlet的優(yōu)先級越高个束,應(yīng)用啟動時就越先加載;

二聊疲、需要在bean定義中配置web請求和Controller的對應(yīng)關(guān)系茬底,例如常用的通過RequestMapping注解來定義web請求和Controller的對應(yīng)關(guān)系

    @RequestMapping("/action")
    public ModelAndView action(
        ......
    )

spring mvc源碼解析:

spring mvc主要涉及2個模塊

  • spring-web
  • spring-webmvc

mvc核心概念

  • view:視圖
  • model:模型
  • controller:控制器

spring mvc核心實(shí)體類/接口

  • View:視圖
  • Handler:對應(yīng)mvc中的控制器
  • HandlerAdapter:handler的調(diào)度器
  • DispatcherServlet:http的請求分發(fā)處理器
  • ModelAndView:handler返回的model和view對象

spring mvc核心類源碼解讀:

  • ContextLoaderListener:
    源碼位置:

決定第一個講ContextLoaderListener,是因?yàn)镃ontextLoaderListener負(fù)責(zé)在項(xiàng)目啟動時掃描spring的Bean配置(比如applicationContext.xml)获洲,加載Bean的定義到IoC容器中去阱表,是spring mvc應(yīng)用的基礎(chǔ)

ContextLoaderListener的源碼如下:

/**
 * Bootstrap listener to start up and shut down Spring's root {@link WebApplicationContext}.
 * Simply delegates to {@link ContextLoader} as well as to {@link ContextCleanupListener}.
 *
 * <p>As of Spring 3.1, {@code ContextLoaderListener} supports injecting the root web
 * application context via the {@link #ContextLoaderListener(WebApplicationContext)}
 * constructor, allowing for programmatic configuration in Servlet 3.0+ environments.
 * See {@link org.springframework.web.WebApplicationInitializer} for usage examples.
 *
 * @author Juergen Hoeller
 * @author Chris Beams
 * @since 17.02.2003
 * @see #setContextInitializers
 * @see org.springframework.web.WebApplicationInitializer
 */
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

    public ContextLoaderListener() {
    }

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


    /**
     * Initialize the root web application context.
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }


    /**
     * Close the root web application context.
     */
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }

}

ContextLoaderListener的核心:
1.讀類注釋可以知道ContextLoaderListener的作用是負(fù)責(zé)啟動和關(guān)閉spring的root webapplicationContext 2.ContextLoaderListener繼承了ServletContextListener接口,重寫了contextInitialized和contextDestroyed方法,這2個方法是和servlet生命周期相結(jié)合的回調(diào)最爬,所以ServletContextListener的功能之一是對servlet的生命周期做監(jiān)聽 3.繼承了ContextLoader類涉馁,通過調(diào)用ContextLoader類中的initWebApplicationContext()/closeWebApplicationContext()2個方法實(shí)現(xiàn)對root webapplicationContext的初始化和銷毀

  • ContextLoader
    initWebApplicationContext()/closeWebApplicationContext()的實(shí)現(xiàn):
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        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);
                    }
                    configureAndRefreshWebApplicationContext(cwac, servletContext);
                }
            }
            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;
        }
    }
public void closeWebApplicationContext(ServletContext servletContext) {
        servletContext.log("Closing Spring root WebApplicationContext");
        try {
            if (this.context instanceof ConfigurableWebApplicationContext) {
                ((ConfigurableWebApplicationContext) this.context).close();
            }
        }
        finally {
            ClassLoader ccl = Thread.currentThread().getContextClassLoader();
            if (ccl == ContextLoader.class.getClassLoader()) {
                currentContext = null;
            }
            else if (ccl != null) {
                currentContextPerThread.remove(ccl);
            }
            servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市烂叔,隨后出現(xiàn)的幾起案子谨胞,更是在濱河造成了極大的恐慌固歪,老刑警劉巖蒜鸡,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異牢裳,居然都是意外死亡逢防,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門蒲讯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來忘朝,“玉大人,你說我怎么就攤上這事判帮【粥遥” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵晦墙,是天一觀的道長悦昵。 經(jīng)常有香客問我,道長晌畅,這世上最難降的妖魔是什么但指? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮抗楔,結(jié)果婚禮上棋凳,老公的妹妹穿的比我還像新娘。我一直安慰自己连躏,他們只是感情好剩岳,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著入热,像睡著了一般拍棕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上才顿,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天莫湘,我揣著相機(jī)與錄音,去河邊找鬼郑气。 笑死幅垮,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的尾组。 我是一名探鬼主播忙芒,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼示弓,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了呵萨?” 一聲冷哼從身側(cè)響起奏属,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎潮峦,沒想到半個月后囱皿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡忱嘹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年嘱腥,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拘悦。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡齿兔,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出础米,到底是詐尸還是另有隱情分苇,我是刑警寧澤,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布屁桑,位于F島的核電站医寿,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏掏颊。R本人自食惡果不足惜糟红,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望乌叶。 院中可真熱鬧盆偿,春花似錦、人聲如沸准浴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽乐横。三九已至求橄,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間葡公,已是汗流浹背罐农。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留催什,地道東北人涵亏。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親气筋。 傳聞我的和親對象是個殘疾皇子拆内,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361

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