Spring Boot Starter Web

2025 年 3 月 18 日 | 3 分钟阅读

spring-boot-starter-web 有两个重要特性

  • 它兼容 Web 开发
  • 自动配置

如果我们想开发一个 Web 应用程序,我们需要在 pom.xml 文件中添加以下依赖

Spring Web 的 Starter 使用 Spring MVC、REST 和 Tomcat 作为默认的嵌入式服务器。单个 spring-boot-starter-web 依赖传递性地拉取所有与 Web 开发相关的依赖。它也减少了构建依赖计数。 spring-boot-starter-web 传递性地依赖于以下内容

  • org.springframework.boot:spring-boot-starter
  • org.springframework.boot:spring-boot-starter-tomcat
  • org.springframework.boot:spring-boot-starter-validation
  • com.fasterxml.jackson.core:jackson-databind
  • org.springframework:spring-web
  • org.springframework:spring-webmvc

默认情况下,spring-boot-starter-web 包含以下 Tomcat 服务器依赖

spring-boot-starter-web 自动配置 Web 开发所需的以下内容

  • Dispatcher Servlet
  • 错误页面
  • 用于管理静态依赖项的 Web JAR
  • 嵌入式 Servlet 容器

Spring Boot 嵌入式 Web 服务器

每个 Spring Boot 应用程序都包含一个嵌入式服务器。 嵌入式服务器作为可部署应用程序的一部分嵌入。 嵌入式服务器的优点是,我们不需要在环境中预安装服务器。 使用 Spring Boot,默认的嵌入式服务器是 Tomcat。 Spring Boot 还支持另外两个嵌入式服务器

  • Jetty 服务器
  • Undertow 服务器

使用另一个嵌入式 Web 服务器

对于 servlet 栈 应用程序, spring-boot-starter-web 通过包含 spring-boot-starter-tomcat 包含了 Tomcat,但我们可以使用 spring-boot-starter-jettyspring-boot-starter-undertow 来代替。

对于 reactive 栈 应用程序, spring-boot-starter-webflux 通过包含 spring-boot-starter-reactor-netty 包含了 Reactor Netty,但我们可以使用 spring-boot-starter-tomcat、spring-boot-starter-jettyspring-boot-starter-undertow 来代替。

Jetty 服务器

Spring Boot 还支持一个名为 Jetty 服务器 的嵌入式服务器。 它是一个 HTTP 服务器和 Servlet 容器,具有提供静态和动态内容的能力。 当需要机器对机器通信时使用它。

如果想在应用程序中添加 Jetty 服务器,我们需要在 pom.xml 文件中添加 spring-boot-starter-jetty 依赖。

记住: 在应用程序中使用 Jetty 服务器时,请确保从 spring-boot-starter-web排除 默认的 Tomcat 服务器。 它可以避免服务器之间的冲突。

我们还可以使用 application.properties 文件自定义 Jetty 服务器的行为。

Undertow 服务器

Spring Boot 提供了另一个名为 Undertow 的服务器。 它也是一个像 Jetty 一样的嵌入式 Web 服务器。 它用 Java 编写,由 JBoss 管理和赞助。 Undertow 服务器的主要优点是

  • 支持 HTTP/2
  • HTTP 升级支持
  • Websocket 支持
  • 提供对 Servlet 4.0 的支持
  • 灵活
  • 可嵌入

记住: 在应用程序中使用 Undertow 服务器时,请确保从 spring-boot-starter-web排除 默认的 Tomcat 服务器。 它可以避免服务器之间的冲突。

我们还可以使用 application.properties 文件自定义 Undertow 服务器的行为。

spring-boot-starter-web vs. spring-boot-starter-tomcat

spring-boot-starter-web 包含包含 spring-boot-starter-tomcat 的 Spring Web 依赖项。 spring-boot-starter-web 包含以下内容

  • spring-boot-starter
  • jackson
  • spring-core
  • spring-mvc
  • spring-boot-starter-tomcat

spring-boot-starter-tomcat 包含与 Tomcat 服务器相关的所有内容。

  • 核心 (core)
  • el
  • 日志
  • websocket

starter-tomcat 具有以下依赖项

我们也可以在不使用嵌入式 Tomcat 服务器的情况下使用 spring-mvc。 如果我们想这样做,我们需要使用 <exclusion> 标签排除 Tomcat 服务器,如下面的代码所示。

 
下一个主题Spring Data JPA