Spring START process

Source: Internet
Author: User

Reprint: https://www.cnblogs.com/luoluoshidafu/p/6442055.html

  1. First, for a Web application that is deployed in a Web container, the Web container provides its global context, which is ServletContext, which provides the hosting environment for the following spring IOC container;

  2. Second, a contextloaderlistener is provided in Web. Xml. When the Web container starts, the container initialization event is triggered, and Contextloaderlistener hears the event and its Contextinitialized method is called, in which spring Initializes a startup context, This context is referred to as the root context, Webapplicationcontext, which is an interface class, specifically, its actual implementation class is Xmlwebapplicationcontext. This is the spring IOC container, whose corresponding bean-defined configuration is specified by the Context-param tag in Web. Xml. After the IOC container is initialized, Spring takes the Webapplicationcontext.rootWEBapplicationCONTEXTattribute as the property key, Store it in ServletContext for easy access;

  3. Again, after the Contextloaderlistener listener is initialized, Start initializing the servlet configured in Web. XML, this servlet can be configured with multiple, for example, the most common Dispatcherservlet, the servlet is actually a standard front-end controller to forward, match, and process each servlet request. The Dispatcherservlet context, when initialized, establishes its own IOC context for holding spring MVC-related beans. The Webapplicationcontext.rootWEBApplication context is used when establishing Dispatcherservlet's own IOC contexts Attribute first gets the previous root context (that is, Webapplicationcontext) from ServletContext as the parent context of its own context. Once you have this parent context, initialize the context that you hold. The work of this dispatcherservlet initializing its own context can be seen in its Initstrategies method, which is about initializing processor mappings, view parsing, and so on. The default implementation class for the context that the servlet holds itself is also mlwebapplicationcontext. After initialization, spring is associated with the name of the servlet (not simply a servlet named key, but through some transformations, the specific self-view source) property is the property key, and it is stored in ServletContext for later use. Each servlet thus holds its own context, which has its own separate bean space, while each servlet shares the same bean, which is defined by the root context (the context initialized in step 2nd).

First, say ServletContext

The Java EE standard specifies that the servlet container needs to initialize a servletcontext as a public environment container for public information when the application project starts. The information in the ServletContext is provided by the container.

Example:

Get the parameters configured in Web. XML by customizing Contextlistener 1. When the container starts, locate the Context-param in the configuration file as the key-value pair in ServletContext 2. Then find the listener, the container calls its contextinitial Ized (Servletcontextevent Event) method, perform one of the following actions, such as: Configuring in Web. xml
<context-param>   <param-name>key</param-name>   <param-value>value123</ Param-value></context-param><listener>    <listener-class> Com.brolanda.contextlistener.listener.contextlistenertest</listener-class></listener>
Once configured, get the corresponding parameter information in the class
Package Com.brolanda.contextlistener.listener;import Javax.servlet.servletcontext;import Javax.servlet.servletcontextevent;import Javax.servlet.servletcontextlistener;public class ContextListenerTest Implements Servletcontextlistener {public        void contextdestroyed (Servletcontextevent event) {        System.out.println ("*************destroy contextlistener*************");    }        @SuppressWarnings ("unused") public    void Contextinitialized (Servletcontextevent event) {        System.out.println ("*************init contextlistener*************");        ServletContext ServletContext = Event.getservletcontext ();        System.out.println ("Key:" +servletcontext.getinitparameter ("key"));    }    }

Execution process:

Web. XML declares application-scoped initialization parameters in the <context-param></context-param> tag

1. When you start a Web project, the container (for example, Tomcat) reads its configuration file, Web. Read two nodes: <listener></listener> and <context-param></ Context-param>2. Immediately thereafter, the container creates a ServletContext (context). Globally shared within the app.

3. The container converts <context-param></context-param> into a key-value pair and gives it to ServletContext.

4. The container creates a class instance in <listener></listener>, that is, the listener is created. The listener must implement a self-servletcontextlistener interface

5. Contextinitialized (Servletcontextevent Event) initialization method in listening

Get ServletContext = Servletcontextevent.getservletcontext () in this method;
            "Context-param value" = Servletcontext.getinitparameter ("Context-param key"); 6. After you get the value of this context-param, you can do something about it. Note that this time your Web project is not fully started yet. This action will be earlier than all servlets. In other words, at this time, you have a <context-param> The key values in the operation will be executed before your Web project is fully started.   web.xml can define two parameters:    One is the global parameter (ServletContext), through the < context-param></context-param>    One is the servlet parameter, by declaring      <init-param in the servlet >                                                           ,         &N Bsp     <param-name>param1</param-name>                  & nbsp                          ,         &NB Sp                  <param-value>avalible in servlet init () </param-value>                                    ,         &NB Sp                         </init-param>      The first parameter in the servlet can be obtained by Getservletcontext (). Getinitparameter ("Context/param")      The second parameter can only be obtained by This.getinitparameter ("param1") in the servlet's init () method  

Second, Spring context container configuration

Spring provides us with a context-initialization listener that implements the Servletcontextlistener interface: Org.springframework.web.context.ContextLoaderListener

Spring provides us with an IOC container that requires us to specify the container's configuration file, which is then initialized and created by the listener. Requires you to specify the address and file name of the configuration file, be sure to use: Contextconfiglocation as the parameter name.

<context-param>    <param-name>contextConfigLocation</param-name>    <param-value>/ web-inf/applicationcontext.xml,/web-inf/action-servlet.xml,/web-inf/jason-servlet.xml</param-value></ Context-param><listener>    <listener-class> Org.springframework.web.context.contextloaderlistener</listener-class></listener>

The listener, by default, reads the Applicationcontext.xml file under/web-inf/. However, after specifying the configuration file path through Context-param, the corresponding configuration file is read and initialized under the path you specify.

Iii. what is initialized after the spring context container is configured?

Now that ServletContext was initialized by the servlet container, what did spring Contextloaderlistener do to initialize it?

1, the servlet container starts, creates a "global context" for the application: ServletContext 2, The container invokes the Contextloaderlistener configured in Web. XML, initializes the Webapplicationcontext context (that is, the IOC container), loads the Context-param specified profile information into the IOC container. Webapplicationcontext is stored as a key-value pair in the ServletContext 3, The container initializes the servlet configured in Web. XML, initializes its own context information servletcontext, and loads the configuration information for its settings into that context.        Sets the Webapplicationcontext to its parent container. 4. All subsequent servlet initializations are created in 3 steps, initializing their own context and setting Webapplicationcontext to their parent context.

For the scope, the contents of the ApplicationContext created by Contextloaderlistener can be referenced in Dispatcherservlet, but not in the reverse. When spring executes ApplicationContext's Getbean, it is found in the parent applicationcontext if the corresponding bean is not found in its own context. This also explains why we can get the beans in the dispatcherservlet that correspond to the ApplicationContext in the Contextloaderlistener.

Iv. reasons for use of:<context:exclude-filter> when spring is configured, Why applicationcontext.xml the controller in the Spring-mvc.xml, and Incloud the controller in the

Now that you know the spring START process, the Web container initializes the Webapplicationcontext as a public context, only the configuration information for service, DAO, and so on is loaded here, and the servlet's own contextual information does not need to be loaded. Therefore, the components of the @controller annotation are excluded from the applicationcontext.xml, and the components of the @controller annotation are loaded in the Dispatcherservlet loaded configuration file. Easy to Dispatcherservlet control and find. Therefore, the configuration is as follows: APPLICATIONCONTEXT.MXL: <context:component-scan base-package= "Com.linkage.edumanage" > <context: Exclude-filter expression= "Org.springframework.stereotype.Controller" type= "annotation"/> </context:   Component-scan> spring-mvc.xml: <context:component-scan base-package= "Com.brolanda.cloud" Use-default-filters= "false" > <context:include-filter expression= "Org.springframework.stereotype.Controller "Type=" annotation "/> </context:component-scan>

Talk about the optimization of SPRINGMVC

Above, we have analyzed the working principle and source code of SPRINGMVC, and found several optimization points in this process:

1.controller If you can keep a singleton, use a singleton as much as possible, which reduces the overhead of creating objects and reclaiming objects. That is, if the controller's class and instance variables can be declared with a method parameter as much as possible in the method's formal parameter declaration, do not declare the class variable and instance variable, This avoids thread-safety issues.

2. The formal parameters in the method of handling the request must be accompanied by a @requestparam annotation, which avoids the process of SPRINGMVC using the ASM framework to read the class file to get the parameter name of the method. Even though SPRINGMVC caches the read-out method parameter names, It is certainly better if you do not read the class file.

3. In the process of reading the source code, it is found that SPRINGMVC does not cache the method of handling the URL, that is, each time to match the method URL in the controller according to the request URL, if the URL and method of the relationship cache, will it bring a performance improvement? What's disgusting is that the servlethandlermethodresolver that is responsible for parsing the URL and method correspondence is a private inner class that cannot directly inherit the class-enhanced code and must be recompiled after that code. Of course, if you cache it, You must consider a cached thread safety issue.

Spring START process

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.