编程知识 cdmana.com

Springboot startup principle

background

1> Everybody knows SpringBoot It's through main Function starts , The tracking code is not found everywhere while(true), Why you can run all the time after starting ?

2> SpringBoot By default tomcat As web Containers . You can also use the pom In file exclusion fall tomcat,denpendency jetty To use jetty. that SpringBoot How to do it differently web How about switching between containers ?

3> Conventional web Containers like jetty It's essentially directly through java start.jar To start up , Then load spring Contextual ,SpringBoot adopt main How functions start web What about the containers ?

This paper discusses these three problems .

 

problem 1 analysis

problem 1 It's simple , It runs all the time after startup because the thread pool is started . The principle is that there is something wrong deamon The thread of is running .Java The virtual machine specification defines that all user threads must run before exiting .

So this principle is the same as starting the thread pool below

The Taoism of programmer cultivation we : Do not assume , To prove . although jetty Common sense is to use thread pools , Let's also track the source code , See where the thread pool is initialized :

 

org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory In class , establish Server Using thread pool as initialization parameter . And then created socket Connect to listen on Port .( about socket There are connections that have not been touched before , You can check it by yourself . It's suggested that you do it yourself .《Java Exception handling summary 》 There are some simple examples in this article that can be used in practice .)

 

Come here , You should all understand why it's been started up all the time . But then there are questions :JettyServletWebServerFactory What is it ?

 

problem 2 analysis

 

About the problem 2, Let's write the simplest class debug once :

 

 

 

Get into SpringAppication.run You can see the source code of , It creates a context, The default is AnnotationConfigServletWebServerApplicationContext. One initialization , stay Bean It's loaded in the definition spring Groundbreaking 5 individual Bean.

 

Keep going down to AbstractApplicationContext Of refresh Method , Execute to onRefresh when , You go into the method and you find that what is actually implemented is

ServletWebServerApplicationContext Of onFresh

 

Only one thing has actually been done here : establish web service .

 

Enter this method ,debug To getWebServerFactory

Take a look at :

Get formal JettyServletWebServerFactory. Why not TomcatServlet Well ?ServletWebServerFactoryAutoConfiguration The source code is a good illustration of this problem . The main idea of the source code is when tomcat Depend on the existence of tomcat, Otherwise, we'll find it in order jetty Existence does not exist , There is no such thing as looking for Undertow Existence does not exist . When you find it, return to this bean As Servlet Factory class .

@Configuration
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@EnableConfigurationProperties({ServerProperties.class})
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {
public ServletWebServerFactoryAutoConfiguration() {
}

@Bean
public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties) {
return new ServletWebServerFactoryCustomizer(serverProperties);
}

@Bean
@ConditionalOnClass(
name = {"org.apache.catalina.startup.Tomcat"}
)
public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
return new TomcatServletWebServerFactoryCustomizer(serverProperties);
}

public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
private ConfigurableListableBeanFactory beanFactory;
public BeanPostProcessorsRegistrar() {
}

public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.beanFactory = (ConfigurableListableBeanFactory)beanFactory;
}

}

public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (this.beanFactory != null) {
this.registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class);
this.registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class);
}
}

private void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class<?> beanClass) {
if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
beanDefinition.setSynthetic(true);
registry.registerBeanDefinition(name, beanDefinition);
}

}
}
}

So far, the second question has come to light .

 

problem 3 analysis

The third problem is traditional web Containers like jetty It's essentially directly through java start.jar To start up , Then load spring Contextual ,SpringBoot adopt main How functions start web Containers .

This question also gave a lot of clues in the process of analyzing the previous problems . Let's review :SpringApplication.run It will create Spring Application context , The default is AnnotationConfigServletWebServerApplicationContext. It will load first Spring Groundbreaking 5 individual Bean. Then it initializes all kinds of Bean factory .

SpringBoot stay ServletWebServerApplicationContext It's overloaded onRefresh Method , Except before Spring default onRefresh In addition to the method createWebServer Method , In this method, to Web The container is initialized .

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
<version>${spring.boot.version}</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-all</artifactId>
</exclusion>
</exclusions>
</dependency>

Because of the choice servlet Containers are similar to using conditional annotation . Because when exclusion fall tomcat after , Only jetty Meet the conditions , So it will load JettyServletWebServerFactory.

adopt getWebServer Method Society new One WebServer object ,new Object's method will call initialize Method , In this method, the container is initialized and started .

The basic principle of container startup is to create a thread pool and network socket . Using threads to process socket read and write content .

 

summary

The text begins with three questions with a little explanation , It's actually using the McKinsey method SCQA framework .

SCQA Architecture is a prominent discussion method in the pyramid model , namely “ situation (Situation)、 Conflict (Complication)、 problem (Question)、 answer (Answer)”. It can help us to be more organized when we present the facts 、 It works .

SCQA It's just McKinsey's conclusion . This method is used by Li Qingzhao :

Last night, it was windy , Deep sleep does not eliminate the wine  ( situation )

Let's ask the roller shutter , But the Begonia is still ( Conflict )

To know whether , To know whether ( problem )

It should be green, fat, red and thin ( answer )

 

The text seems to answer the question step by step , It's actually about how to see spring Source code , understand spring A process of principle . namely : Look at... With questions ,debug Tracking source validation Methods .

版权声明
本文为[Programming life]所创,转载请带上原文链接,感谢

Scroll to Top