SpringBoot嵌入式Servlet配置原理

SpringBoot修改服务器配置

  • 配置文件方式方式修改,实际修改的是ServerProperties文件中的值
server.servlet.context-path=/crud
server.port=8081
  • Java代码方式修改。通过实现WebServerFactoryCusomizer接口来获取到达ConfigurableServletWebServerFactory的通道,ConfigurableServletWebServerFactory中提供了很多的方法用来修改服务器配置。
@Component
public class ServletHandler implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> { @Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.setPort(8083);
}
}

SpringBoot使用原生web组件

在之前的Web项目中,我们会通过web.xml来注册三大组件,在springboot中我们通过提供的类注册三大组件

  • Servlet。通过ServletRegistrationBean来注册一个Servlet
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registration = new ServletRegistrationBean(new MyServlet(),"/hello");
return registration;
}
  • Filter。通过FilterRegistrationBean来祖册Filter
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new MyFilter());
filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello"));
return filterRegistrationBean ;
}
  • Listener。通过ServletListenerRegistrationBean来注册一个监听器
@Bean
public ServletListenerRegistrationBean myServletListener(){
ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean();
registrationBean.setListener(new MyServletContextListener());
return registrationBean ;
}

Spring使用其他服务器

SpringBoot提供了三个服务器工厂,Tomcat,Jetty,Undertow,默认使用了Tomcat

  • 使用Jetty。需要排除Tomcat依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency> <dependency>
<artifactId>spring-boot-starter-jetty</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>
  • 使用Undertow服务器。同Jetty一样
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency> <dependency>
<artifactId>spring-boot-starter-undertow</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>

SpringBoot服务器自动配置原理

  • Springboot通过WebServerInitializedEvent来实现服务器自动配置,通过这个类来加载一个WebServer
public abstract class WebServerInitializedEvent extends ApplicationEvent {
protected WebServerInitializedEvent(WebServer webServer) {
super(webServer);
}
  • 通过WebServer来创建固定的服务器。

    • TomcatWebServer
    • JettyWebServer
    • NettyWebServer
    • UndertowWebServer
public interface WebServer {
void start() throws WebServerException; void stop() throws WebServerException; int getPort();
}

SpringBoot启动Tomcat服务器的过程

  • SpringBoot启动方法
SpringApplication.run(DemoApplication.class, args)

  • 调用SpringAllication.run方法返回了ConfigurableApplicationContext对象
 public ConfigurableApplicationContext run(String... args) {
context = this.createApplicationContext();//创建了一个Application对象
this.refreshContext(context);//刷新ApplicationContext
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch(this.webApplicationType) {
case SERVLET:
contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
break;
case REACTIVE:
contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
break;
default:
contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
}
} catch (ClassNotFoundException var3) {
throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
}
} return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}
  • 创建了AnnotationConfigReactiveWebServerApplicationContext这个类最终实现了AbstractApplicationContext
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();
}
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory); try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
//调用子类的刷新方法,最终调用的是创建ApplicationContext容器中所选择的容器即ServletWebServerApplicationContext类中的方法
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
} this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
} }
}
protected void onRefresh() {
super.onRefresh(); try {
//创建了web容器
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) {
//创建一个web服务器,
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() {
//获取了容器中ServletWebServerFactory类型的容器
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 {
//创建了web服务器
return (ServletWebServerFactory)this.getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
}
}
  • 通过this.getWebServerFactory方法创建了web服务器,通过this.getBeanFactory()获取了容器中所存在的类型为ServletWebServerFactory类型的容器,然后获取bean创建了Tomcat对象

SpringBoot嵌入式Servlet配置原理的更多相关文章

  1. SpringBoot嵌入式Servlet容器

    SpringBoot默认是将Tomcat作为嵌入式的servlet容器. 问题: 如何修改嵌入式的servlet容器? 1)在配置文件中设置对应的属性值 server.port=8081 # Tomc ...

  2. SpringBoot的自动配置原理过程解析

    SpringBoot的最大好处就是实现了大部分的自动配置,使得开发者可以更多的关注于业务开发,避免繁琐的业务开发,但是SpringBoot如此好用的 自动注解过程着实让人忍不住的去了解一番,因为本文的 ...

  3. SpringBoot之自动配置原理

    我在前面的Helloworld的程序中已经分析过一次,配置原理了: 1).SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration 2).@En ...

  4. 面试题: SpringBoot 的自动配置原理

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 3.Spring Boot 的自动配置原理 package com.mmall; import org. ...

  5. SpringBoot的自动配置原理

    一.入口 上篇注解@SpringBootApplication简单分析,说到了@SpringBootApplication注解的内部结构, 其中@EnableAutoConfiguration利用En ...

  6. SpringBoot的启动配置原理

    一.启动流程 创建SpringApplication对象 public class SpringApplication { public SpringApplication(Class... prim ...

  7. 18、配置嵌入式servlet容器(2)

    使用其他Servlet容器 -Jetty(长连接) -Undertow(不支持jsp) 替换为其他嵌入式Servlet容器   默认支持: Tomcat(默认使用) Jetty: <depend ...

  8. SpringBoot源码学习系列之嵌入式Servlet容器

    目录 1.博客前言简单介绍 2.定制servlet容器 3.变换servlet容器 4.servlet容器启动原理 SpringBoot源码学习系列之嵌入式Servlet容器启动原理 @ 1.博客前言 ...

  9. SpringBoot自动配置原理

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 回顾前面Spring的文章(以学习的顺序排好): S ...

随机推荐

  1. PQSQL 按照时间进行分组

    按照时间分组时一般是按照年.月.日进行分组,不会把时分秒也算进去,所以需要把时间戳提取出所需要的时间段,本质上是把时间戳格式化成对应形式的字符串,这个过程需要用to_char(timestamp, t ...

  2. TensorFlow——训练模型的保存和载入的方法介绍

    我们在训练好模型的时候,通常是要将模型进行保存的,以便于下次能够直接的将训练好的模型进行载入. 1.保存模型 首先需要建立一个saver,然后在session中通过saver的save即可将模型保存起 ...

  3. java 支持分词的高性能拼音转换工具,速度是 pinyin4j 的两倍

    pinyin pinyin 是 java 实现的高性能中文拼音转换工具. 变更日志 创作目的 想为 java 设计一款便捷易用的拼音工具. 如何为 java 设计一款高性能的拼音转换工具 pinyin ...

  4. Pycharm 中的翻译工具

    对于开发来说,大多数哥们英文欠缺,比如在下,我们大多数使用的开发工具是IDEA,IDEA 很强大,开发起来顺手. 废话不多说,让我们看一下如何使用翻译器. 打开Pycharm 的setting 设置, ...

  5. python爬虫——selenium+firefox使用代理

    本文中的知识点: python selenium库安装 firefox geckodriver的下载与安装 selenium+firefox使用代理 进阶学习 搭建开发环境: selenium库 fi ...

  6. 假期续命充电——简单上手tesorflow2 框架

    谈到深度学习,就不得不谈到tensorflow 在tensorflow之后出了2.0版本,相比之前有了很大的改变,趁着假期赶紧冲冲冲! 稍微学习了一些基础,做一个自我总结,作为一些基础的知识不再过多重 ...

  7. 打包一份py给大家用!!!

    好不容易写完了代码,却发现对面无法使用自己的python代码,其无奈可想而知 在这里就给大家介绍一下pyinstaller的简单用法 你所需要的就是在电脑上安装好 https://blog.csdn. ...

  8. Nginx的踩坑实录

    1.昨天在为一个新项目配置地址转发,搞了很久都没生效,日志也没有问题,但就是没到转发的目标机器上. nginx.conf 配置如下: location /prism{ proxy_pass http: ...

  9. 关于SpringDataJpa中测试出现StackOverflowError错误问题

    在使用SpringDataJpa进行多表查询时,使用导航查询,每次都出现 StackOverflowError错误, 经过查找资料,网上百度,终于找到原因, StackOverflowError 是栈 ...

  10. Wordpress4.9.6 任意文件删除漏洞复现分析

    第一章 漏洞简介及危害分析 1.1漏洞介绍 WordPress可以说是当今最受欢迎的(我想说没有之一)基于PHP的开源CMS,其目前的全球用户高达数百万,并拥有超过4600万次的超高下载量.它是一个开 ...