In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail about the startup principle of SpringBoot embedded web container. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
The SpringBoot application starts the code executed in the run method SpringApplication.java @ SpringBootApplication@EnableAsync / / using the asynchronous annotation @ Async needs to add @ EnableAsync@MapperScan ("springboot.dao") / / the indispensable function is to scan all mapper assemblies under the dao package public class HelloApplication {public static void main (String [] args) {SpringApplication.run (HelloApplication.class,args);} public static ConfigurableApplicationContext run (Class primarySource, String...) Args) {return run (new Class [] {primarySource}, args);} public static ConfigurableApplicationContext run (Class [] primarySources, String [] args) {return (new SpringApplication (primarySources)) .run (args);}
Private void refreshContext (ConfigurableApplicationContext context) {this.refresh (context); if (this.registerShutdownHook) {try {context.registerShutdownHook ();} catch (AccessControlException var3) {}} protected void refresh (ApplicationContext applicationContext) {Assert.isInstanceOf (AbstractApplicationContext.class, applicationContext); ((AbstractApplicationContext) applicationContext). Refresh () } method public final void refresh () throws BeansException executed by ServletWebServerApplicationContext.java, IllegalStateException {try {super.refresh ();} catch (RuntimeException var2) {this.stopAndReleaseWebServer (); throw var2;}} protected void onRefresh () {super.onRefresh (); try {this.createWebServer () } catch (Throwable var2) {throw new ApplicationContextException ("Unable to start web server", var2);}} private void createWebServer () {WebServer webServer = this.webServer; ServletContext servletContext = this.getServletContext (); if (webServer = = null & & servletContext = = null) {ServletWebServerFactory factory = this.getWebServerFactory (); this.webServer = factory.getWebServer (new ServletContextInitializer [] {this.getSelfInitializer ()}) } else if (servletContext! = null) {try {this.getSelfInitializer () .onStartup (servletContext);} catch (ServletException var4) {throw new ApplicationContextException ("Cannot initialize servlet context", var4);}} this.initPropertySources ();} protected ServletWebServerFactory getWebServerFactory () {String [] beanNames = this.getBeanFactory (). GetBeanNamesForType (ServletWebServerFactory.class) If (beanNames.length = = 0) {throw new ApplicationContextException ("Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.");} else if (beanNames.length > 1) {throw new ApplicationContextException ("Unable to start ServletWebServerApplicationContext due to multiple ServletWebServerFactory beans:" + StringUtils.arrayToCommaDelimitedString (beanNames));} else {return (ServletWebServerFactory) this.getBeanFactory () .getBean (beanNames [0], ServletWebServerFactory.class) }} / / configure embedded servlet container @ Bean public WebServerFactoryCustomizer MyCustomizer () {return new WebServerFactoryCustomizer () {@ Override public void customize (ConfigurableWebServerFactory factory) {factory.setPort (8081);}};};} SpringBoot version 2.x embedded Servlet container automatic configuration principle and startup principle 1, version description
Spring Boot version 2.x embedded Servlet container autoconfiguration is customized through WebServerFactoryCustomizer customizer, while in Spring Boot version 1.x we customize it through EmbeddedServletContainerCustomizer embedded Servlet container customizer. Since all the materials I have seen before are 1.x, but I am using 2.x, I will record the auto-configuration principle and startup principle of embedded Servlet container in 2.x.
II. Summary
The auto-configuration principle and startup principle of embedded Servlet container have three major steps:
Steps:
SpringBoot automatically creates the corresponding WebServerFactoryCustomizer (web service factory customizer) based on the imported dependency information.
WebServerFactoryCustomizerBeanPostProcessor (the post processor of the web service factory customizer component) gets all the components of the type web service factory customizer (including implementing the WebServerFactoryCustomizer interface, custom customizer components), and then calls the customize () custom interface to customize the Servlet container configuration.
The embedded Servlet container factory creates the tomcat container, initializes and starts the container.
Third, the principle of automatic configuration of embedded Servlet container (taking Tomcat as an example)
1. First find EmbeddedWebServerFactoryCustomizerAutoConfiguration, where we can see the servlet containers supported by SpringBoot
/ / servlet containers supported by SprinBoot have three Tomcat, Jetty and Undertow, but the default configuration is Tomcat / / embedded Undertow @ Configuration (proxyBeanMethods = false) @ ConditionalOnClass ({Undertow.class, SslClientAuthMode.class}) public static class UndertowWebServerFactoryCustomizerConfiguration {public UndertowWebServerFactoryCustomizerConfiguration () {} @ Bean public UndertowWebServerFactoryCustomizer undertowWebServerFactoryCustomizer (Environment environment, ServerProperties serverProperties) {return new UndertowWebServerFactoryCustomizer (environment, serverProperties) }} / / embedded Jetty @ Configuration (proxyBeanMethods = false) @ ConditionalOnClass ({Server.class, Loader.class, WebAppContext.class}) public static class JettyWebServerFactoryCustomizerConfiguration {public JettyWebServerFactoryCustomizerConfiguration () {} @ Bean public JettyWebServerFactoryCustomizer jettyWebServerFactoryCustomizer (Environment environment, ServerProperties serverProperties) {return new JettyWebServerFactoryCustomizer (environment, serverProperties) }} / embedded Tomcat @ Configuration (proxyBeanMethods = false) @ ConditionalOnClass ({Tomcat.class, UpgradeProtocol.class}) public static class TomcatWebServerFactoryCustomizerConfiguration {public TomcatWebServerFactoryCustomizerConfiguration () {} @ Bean public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer (Environment environment, ServerProperties serverProperties) {return new TomcatWebServerFactoryCustomizer (environment, serverProperties);}}
2. Preparation
1) make a breakpoint in the following position
2) Click TomcatWebServerFactoryCustomizer, which is the return above, and make a breakpoint in the following location
3) then in the debug program, we can see the following information in the console
3. Analyze from bottom to top according to the above picture. When we start the springboot application, we always run the main method of the main program directly, and then call the run method in it, as shown in the following figure
4. After calling the run method, come back to the refreshContext method, which is to help us create the IOC container object, initialize the container and create each component in the container
5. After calling the reflesh method to refresh the IOC container, go to the onreflesh method, call the createWebServer () method, and create the WebServer
6. Come to the createWebServer () method, which can finally obtain a web service factory that matches the Servlet type imported by the current application (that is, the first step in the summary, according to the imported dependencies), and the corresponding WebServerFactoryCustomizer (Web service factory customizer) can be obtained through the factory.
Note: after the execution of createWebServer (), we actually come to EmbeddedWebServerFactoryCustomizerAutoConfiguration, and then configure which Web server according to the condition (configuration dependency)
By looking at the subclasses of ServletWebServerFactory, we can see that three of them are Tomcat, Jetty and Undertow. According to our configuration, what we get here is TomcatWebServerFactoryCustomizer.
At this point, the TomcatWebServerFactoryCustomizer component is created, and the corresponding service configuration class has been added to the IOC container.
7. Because when a component in the container wants to create an object, it alerts the post processor and then goes to WebServerFactoryCustomizerBeanPostProcessor (the post processor of the web service factory customizer component), which is responsible for performing initialization before the bean component is initialized. It first gets all the components of type WebServerFactoryCustomizerBeans (web service factory customizer) from the IOC container
Call the customize () customization method through the TomcatWebServerFactoryCustomizer obtained by the post processor to obtain the Servlet container-related configuration class ServerProperties for automatic configuration
At this point, the automatic configuration of the embedded Servlet container is complete.
Note: two solutions for configuring embedded Servlet containers can be obtained from source code analysis:
1. In the global configuration file, use server.xxx to modify the configuration related to server:
Server.port=8081server.tomcat.xxx...
2. Implement the WebServerFactoryCustomizer interface, override its customize () method, and customize the configuration of the container:
@ FunctionalInterfacepublic interface WebServerFactoryCustomizer {void customize (T factory);} IV. Startup principle of embedded Servlet container (take Tomcat as an example)
1. After the application starts, according to the imported dependency information, the corresponding Servlet container factory is created, the TomcatServletWebServerFactory is created, and the getWebServer () method is called to create the Tomcat container: (in fact, the getWebServer method in ServletWebServerFactory is overridden)
Find the following getTomcatWebServer method
2. Then click in to analyze the TomcatWebServer's parametric constructor and execute the initialize () method
3. Click in to find that you can start Tomcat by calling the start method.
This is the end of the article on "what is the startup principle of SpringBoot embedded web container". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.