Spring web boot is a magic horse principle. I read the source code for a day and wrote a demo at night. When spring starts a Web container, it initializes its own IOC container by using Servlet or defining a listener. There is also a dispatchservlet to inject the required classes into your actionbean.
I define a webloader class to inherit Org. springframework. web. context. contextloader and rewrite his createwebapplicationcontext method. I only change one sentence in the source code to WAC. setconfiglocation (SC. getinitparameter ("xcontextconfiglocation "));
This WAC is configurablewebapplicationcontext
The default contextconfiglocation parameter in spring source code needs to be defined every time
<Context-param>
<Param-Name> contextconfiglocation </param-Name>
<Param-value> WEB-INF/c1.xml </param-value>
</Context-param>
Now I have changed
Spring finds the following in Web. xml.
<Context-param>
<Param-Name> xcontextconfiglocation </param-Name>
<Param-value> WEB-INF/c2.xml </param-value>
</Context-param>
C1.xml defines a sentence <bean id = "B1" class = "com. bean1"/>
C2.xml defines a sentence <bean id = "B2" class = "com. bean2"/>
Then I define a servlet to automatically load when the Web Container starts.
<Servlet>
<Servlet-Name> context </servlet-Name>
<Servlet-class> com. initweb </servlet-class>
<Load-on-startup> 0 </load-on-startup>
</Servlet>
The init method of this servlet is
@ Override
Public void Init () throws servletexception {
System. Out. println ("Hei I am init ");
Servletcontext SC = getservletcontext ();
Webapplicationcontext parent = webapplicationcontextutils. getwebapplicationcontext (SC );
Webloader loader = new webloader ();
Webapplicationcontext WAC = loader. createwebapplicationcontext (SC, parent );
System. Out. println (WAC. getbeandefinitioncount ());
SC. setattribute (webapplicationcontext. root_web_application_context_attribute, WAC );
Super. INIT ();
}
I write in JSP
<%
Webapplicationcontext WAC = webapplicationcontextutils
. Getrequiredwebapplicationcontext (getservletcontext ());
Bean1 b1 = (bean1) WAC. getbean ("B1 ");
Out. println (b1.getname () + "<br/> ");
Bean2 b2 = (bean2) WAC. getbean ("B2 ");
Out. println (b2.getname () + "<br/> ");
%>
The output result is
I am bean one!
I am bean two!
In servlet, The applicationcontext in the Web container is overwritten by me. Originally, only the bean in c1.xml is loaded by default, I extracted the webapplicationcontext in the container and used it as the c2.xml parent to create a new webapplicationcontext and then loaded it to the servletcontext. Now the applicationcontext in the web context contains the beans in two configuration files.
In the final analysis, the basic principle of spring injection in Web containers is to initialize webapplicationcontext and store it in servletcontext when the Web Container starts. Use this webapplicationcontext. root_web_application_context_attribute to read the current IOC container.