SpringBoot如何默认引入Tomcat,并自动装配

SpringBoot引入Tomcat

其实就是直接在pom.xml文件默认引入Tomcat的。。。。

 1     <dependency>
 2       <groupId>org.springframework.boot</groupId>
 3       <artifactId>spring-boot-starter-json</artifactId>
 4       <version>2.3.7.RELEASE</version>
 5       <scope>compile</scope>
 6     </dependency>
 7     <dependency>
 8       <groupId>org.springframework.boot</groupId>
 9       <artifactId>spring-boot-starter-tomcat</artifactId>
10       <version>2.3.7.RELEASE</version>
11       <scope>compile</scope>
12     </dependency>

自动装配

1. 通过spring-boot-autoconfigure的spring.factories中key为org.springframework.boot.autoconfigure.EnableAutoConfiguration,值为ServletWebServerFactoryAutoConfiguration引入配置文件

2. 通过@import注解引入EmbeddedTomcat的bean

3. 可以看到这里有@ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })注解,由于spring-boot-web默认引入Tomcat.jar,所以这里会进行bean的注入,

ServletWebServerFactoryAutoConfiguration类上的注解,其实也引入了Jetty、undertow,只是没有相应的jar包,所以没有注入相应的bean

 

4. 注入bean之后,怎么启动Tomcat呢?答案就在org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext里面createWebServer方法,这里类也是继承AbstractApplicationContext类的

5. 该方法里面会调用通过bean的byType去找servlet工厂bean,至此就找到第三步注入的bean--TomcatServletWebServerFactory

 1 protected ServletWebServerFactory getWebServerFactory() {
 2         // Use bean names so that we don't consider the hierarchy
 3         String[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
 4         if (beanNames.length == 0) {
 5             throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing "
 6                     + "ServletWebServerFactory bean.");
 7         }
 8         if (beanNames.length > 1) {
 9             throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple "
10                     + "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
11         }
12         return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
13     }

6. 剩下就是调用Tomcat工厂实现socket的监听了,具体可以参考 https://blog.csdn.net/qq_31086797/article/details/107418371

 

posted @ 2021-08-29 00:00  冰肌玉骨小香脐  阅读(890)  评论(0编辑  收藏  举报