SPRINGMVC Loading Webapplicationcontext Source Analysis

Source: Internet
Author: User

The spring Framework provides a full-featured MVC module for building Web applications called Spring MVC, which builds a stable set of Java Web projects through Spring core+spring MVC. This paper introduces the core implementation principle of Spring MVC source code analysis.

The Tomcat server boot portal file is Web. XML, which allows you to load the data required by spring MVC by configuring the associated listener and servlet. The simplest configuration based on spring MVC is as follows.

  1. <!--load Spring configuration file--
  2. <context-param>
  3. <param-name>contextconfiglocation</param-name>
  4. <param-value>
  5. Classpath:spring-context*.xml
  6. </param-value>
  7. </context-param>
  8. <listener>
  9. <listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class>
  10. </listener>
  11. <!--loading Spring MVC--
  12. <servlet>
  13. <servlet-name>spring3mvc</servlet-name>
  14. <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class >
  15. <init-param>
  16. <param-name>contextconfiglocation</param-name>
  17. <param-value>
  18. Classpath:spring-mvc*.xml
  19. </param-value>
  20. </init-param>
  21. <load-on-startup>1</load-on-startup>
  22. </servlet>
  23. <servlet-mapping>
  24. <servlet-name>spring3mvc</servlet-name>
  25. <url-pattern>/</url-pattern>
  26. </servlet-mapping>

    • Create a container

Contextloaderlistener a Web-context-level listener creates a applicationcontext when the server is started and loads the configured spring bean into XML.

Dispatcherservlet is a request distribution controller, and all matching URLs are executed through the servlet distribution, and the spring MVC-related configuration is initialized when the Servlet object is created.

In Web. XML, we see that the spring-related Contextloaderlistener can be configured based on both the Dispatcherservlet and the, and it is worth noting that the ApplicationContext context objects that load spring are not merged The http://blog.csdn.net/madun/article/details/8988860 can be referenced in detail. So personally, the MVC-related spring configuration is loaded by the Dispatcherservlet, while the rest of the JavaBean are handed to Contextloaderlistener for loading.

First, Contextloaderlistener

Contextloaderlistener is a listener that implements the Servletcontextlistener interface. The Contextinitialized method is triggered when the project is started (this method mainly completes the creation of the ApplicationContext object). The Contextdestroyed method is triggered when the project is closed (the method performs a applicationcontext cleanup operation).

Java code
    1. Public class Contextloaderlistener extends Contextloader implements Servletcontextlistener

Conextloaderlistener the process of loading the spring context can be expressed, and the yellow block is the core code.



A brief introduction to the running process:

① triggers the Contextinitialized method when the project is started, and the method does one thing: Create a Spring context object from the Initwebapplicationcontext method of the parent class Contextloader.

The ②initwebapplicationcontext method does three things: Create a webapplicationcontext, and load the corresponding spring file to create the bean instance inside it ; put Webapplicationcontext into ServletContext (which is the global variable of the Java Web).

③createwebapplicationcontext creates a context object that supports user-defined context objects, but must inherit from Configurablewebapplicationcontext, and spring MVC uses Configurablewebapplicationcontext by default as an implementation of ApplicationContext (which is just an interface).

The ④configureandrefreshwebapplicationcontext method is used to encapsulate ApplicationContext data and initialize all related bean objects. It reads the configuration named Contextconfiglocation from Web. XML, which is the spring data source setting, and then it is placed in the ApplicationContext. Finally, the legendary Refresh method is called to perform the creation of all Java objects.

⑤ finished ApplicationContext is created after it is put into servletcontext, note that it stores the key value constant.

Java code
    1. Servletcontext.setattribute (Webapplicationcontext.root_web_application_context_attribute, this.context);
    2. Constant
    3. Public static final String Root_web_application_context_attribute = Webapplicationcontext. Class.getname () + ".  ROOT ";

Note: The IOC container object to get the Contextloader level can be written like this:

    1. Webapplicationcontext Rootcontext = Webapplicationcontextutils.getwebapplicationcontext (GetServletContext ());

Second, Dispatcherservlet

Dispatcherservlet is the implementation of the front-end controller design pattern, providing a centralized access point for spring WEB MVC, responsible for assigning responsibilities, and seamlessly integrating with the spring IOC container to get all the benefits of spring.

To understand how dispatcherservlet loads a container, you need to understand its inheritance first, as shown in:


If the <load-on-startup>1</load-on-startup> of the servlet is set in Web. XML, it is started with the project, and we know that the Init method is called first when Servelt is created. So the Httpservletbean that inherits the HttpServlet is the key entrance. Then the entire code runs as shown in the process.


The ①httpservletbean.init method performs the initialization of the Initservletbean method, which, of course, is an empty method in Httpservletbean, so a subclass rewrite is required.

②frameworkservlet.initservletbean subclasses, overriding the Initservletbean method, the most central operation of the method is to call Initwebapplicationcontext () Executes the context bean initialization.

The ③frameworkservlet.initwebapplicationcontext method first obtains its own parent context (that is, the Contextloaderlistener initialization succeeds Webapplicationcontext), and then creates or obtains the current Servelet's Webapplicationcontext.

④ Whether you create it yourself or get an existing webapplicationcontext, Eventually, the servelt level of Webapplicationcontext executes the Configureandrefreshwebapplicationcontext () method to initialize the context container.

A complete IOC container can be created with the steps above, and after the container is created, Dispatcherservlet does one thing: Initialize the Servelt controller prerequisite object, which is in Initwebapplicationcontext () method is implemented by calling the Onrefresh (WAC) method. And Onrefresh has been rewritten, if you want to know how to initialize the servlet controller prerequisites, you can view Dispatcherservlet's Onrefresh method.

Java code
    1. /**
    2. * This implementation calls {@link #initStrategies}.
    3. */
    4. @Override
    5. protected void Onrefresh (ApplicationContext context) {
    6. Initstrategies (context);
    7. }
    8. /**
    9. * Initialize The strategy objects that this servlet uses.
    10. * <p>may is overridden in subclasses in order to initialize further strategy objects.
    11. */
    12. protected void Initstrategies (ApplicationContext context) {
    13. Initmultipartresolver (context);
    14. Initlocaleresolver (context);
    15. Initthemeresolver (context);
    16. Inithandlermappings (context);
    17. Inithandleradapters (context);
    18. Inithandlerexceptionresolvers (context);
    19. Initrequesttoviewnametranslator (context);
    20. Initviewresolvers (context);
    21. Initflashmapmanager (context);
    22. }

SPRINGMVC Loading Webapplicationcontext Source Analysis

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.