Spring Source Learning Notes (1)

Source: Internet
Author: User

Springmvc Source Learning Notes (i)

Preface----

Recently spent some time to read the "Spring Source depth Analysis" This book, is the introduction of Spring Source bar. Intend to write a series of articles, recall the contents of the book, summarize the code of the running process. Recommend those and I did not contact the SSH framework source and want to learn, read Shangjia authoring "Spring Source Depth Analysis" This book, will be a good introduction.

Enter the text, first paste the picture of Springmvc (from https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html)

    

The general flow of SPRINGMVC is Dispatcherservlet, handlermapping, Controller------------Modelandview Viewresol Ver

View, a little study of the students should be very familiar with the source of the study is based on the process of SPRINGMVC step-in-depth.

Standard for use with SPRINGMVC: dispatcherservlet and contextconfiglocation and Contextloaderlistener in the Web. xml File the configuration

1 <!--configuration start IOC container Listener--2 <context-param> 3 <param-name>contextconfiglocation</param-name> 4 <param-value>classpath:applicationContext.xml</param-value> 5 </context-p Aram> 6 7 <listener> 8 <listener-class>org.springframework.web.context.Contextloaderlistener</listener-class> 9 </listener>10 <!--configuration Springmvc dispatcherservlet-->12 <servlet >13 <servlet-name>springdispatcherservlet</servlet-name>14 &LT;SERVLET-CLASS&GT;ORG.SPRINGF Ramework.web.servlet.Dispatcherservlet</servlet-class>15 <load-on-startup>1</load-on-startup>16 </servlet>17 <serv let-mapping>19 <servlet-name>springdispatcherservlet</servlet-name>20 <url-pattern>/& Lt;/url-pattern>21 </servlet-mapping>

Among them, Contextloaderlistener implements the Servletcontextlistener, overriding the Contextinitialized () method.

1 public class Contextloaderlistener extends Contextloader implements Servletcontextlistener {2 public         } 4  5     public Contextloaderlistener (Webapplicationcontext context) {6         Super } 8 9 Public void< c11> contextinitialized (Servletcontextevent event) {This.  Initwebapplicationcontext  }12 public void contextdestroyed (servletcontextevent event) { + this }17}       

  

There is a initwebapplicationcontext () definition of the method in the parent class Contextloader.

1 publicWebapplicationcontext Initwebapplicationcontext (ServletContext servletcontext) {2 if (Servletcontext.getattribute (webapplicationcontext.root_web_application_context_attribute)! = null{//First step: Existence verification 3 throw new IllegalStateException ("Cannot initialize context because there is already a roo T application context Present-check Whether you had multiple contextloader* definitions in your web.xml! "); 4} else{5 Log logger = Logfactory.getlog (contextloader.class); 6 ServletContext.log ("Initializing Spring root Webapplicationcontext"); 7 if(Logger.isinfoenabled ()) {8 Logger.info ("Root webapplicationcontext:initialization started")); 9}10 One long startTime =System.currenttimemillis ();{if (This.context = = NULL) {//Second step: Initialize context15 This.context = this.Createwebapplicationcontext(ServletContext); 16}17 if (This.context instanceofConfigurablewebapplicationcontext) {Configurablewebapplicationcontext CWAC = (configurablewebapplicationcontext) This. context;20 if (!  Cwac.isactive ()) {if (cwac.getparent () = = null ) {ApplicationContext parent = this . Loadparentcontext ( ServletContext);  cwac.setparent (parent); }25-this . Configureandrefreshwebapplicationcontext (CWAC, ServletContext); }28 }29//Third step: Record in ServletContext Middle of   Servletcontext.setattribute (Webapplicationcontext.root_web_application_context_attribute, This.context);   ClassLoader CCL =  thread.currentthread (). Getcontextclassloader (); if (CCL = = Contextloader.class . getClassLoader ()) {CurrentContext = this . context;34} else if (CCL! = null ) {  currentcontextperthread.put   (CCL, this . Context); Fourth step: Put into the current thread. }37 }38 this.context;         

In the second step, the createwebapplicationcontext () method creates the Webapplicationcontext instance.

1     protected webapplicationcontext createwebapplicationcontext (ServletContext SC) {2          This . Determinecontextclass                (SC); First step: Get the class Type 3         if (! Configurablewebapplicationcontext.class. IsAssignableFrom (Contextclass)) {//Second step: Judging type 4             throw new Applica Tioncontextexception ("Custom context class [" + Contextclass.getname () + "] is not of type [" + Configurablewebapplication Context.class.getName () + "]"); 5         } else {6             return }8}     

In the first step, determinecontextclass () Gets the class type of the Webapplicationcontext.

Protected class<?>Determinecontextclass (ServletContext servletcontext) {String contextclassname = ServletContext.Getinitparameter("Contextclass"); First step: Get the property if (contextclassname! = null ) {Try  {return  Classutils.forn        Ame (Contextclassname, Classutils.getdefaultclassloader ()); Second step: The property is not empty, reflection creates} catch  (ClassNotFoundException var4) {throw new Applicationcontextexception ("Failed To load custom context class ["+ Contextclassname +"] ", VAR4);}} else  {contextclassname =   defaultstrategies  . GetProperty (  Webapplicationcontext.class . GetName ()); Third step: If the property is empty, try  {return classutils.forname (Contextclassname, Contextloader.class ) is loaded from the configuration file. getClassLoader ()); } catch  (ClassNotFoundException var5) {throw new Applicationcontextexception ("Failed to load Default context class ["+ Contextclassname +"] ", VAR5)}}}           

The code is relatively simple, mainly the source of Defaultstrategies.getproperty () . In a static code block in Contextloader, the property is initialized and the configuration file is loaded.

    Static {        try {            Classpathresource resource = new Classpathresource ("contextloader.properties ", Contextloader.class);             = propertiesloaderutils.loadproperties (Resource);        } catch (IOException var1) {            throw New IllegalStateException ("Could not load ' contextloader.properties ':" + var1.getmessage ());} Currentcontextperthread = new Concurrenthashmap (1);}      

Contextloader.properties position.

After the above steps, SPRINGMVC has initialized the Webapplicationcontext and set it in ServletContext, and put it into the current thread. The next article goes into the dispatcherservlet process.

Originally wanted to paste only the key code, but feel less the prepared code, the whole logic seems to be very worried, so copy all the code. The overall knowledge from the "Spring Source depth analysis" content, just to find the code in IntelliJ idea, the logic copy paste, as a review and notes. Welcome to Exchange!!!

Spring Source Learning Notes (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.