开始

1. Spring Boot 简介

Spring Boot 可帮助您创建可以运行的基于 Spring 的独立生产级应用程序。 我们对 Spring 平台和第三方库持固执己见的看法,因此您可以毫不费力地开始使用。 大多数 Spring Boot 应用程序只需要很少的 Spring 配置。spring-doc.cadn.net.cn

您可以使用 Spring Boot 创建可使用以下java -jar或更传统的战争部署。spring-doc.cadn.net.cn

我们的主要目标是:spring-doc.cadn.net.cn

  • 为所有 Spring 开发提供极其快速且可广泛访问的入门体验。spring-doc.cadn.net.cn

  • 开箱即用,但当需求开始与默认值不同时,请迅速离开。spring-doc.cadn.net.cn

  • 提供一系列大型项目通用的非功能性功能(例如嵌入式服务器、安全性、指标、运行状况检查和外部化配置)。spring-doc.cadn.net.cn

  • 绝对不需要代码生成(当不针对本机图像时),也不需要 XML 配置。spring-doc.cadn.net.cn

2. 系统要求

Spring Boot 3.0.13 需要 Java 17,并且与 Java 21 兼容。还需要 Spring Framework 6.0.14 或更高版本。spring-doc.cadn.net.cn

为以下构建工具提供显式构建支持:spring-doc.cadn.net.cn

构建工具 版本

Maven 系列spring-doc.cadn.net.cn

3.5+spring-doc.cadn.net.cn

Gradlespring-doc.cadn.net.cn

7.x(7.5 或更高版本)和 8.xspring-doc.cadn.net.cn

2.1. Servlet 容器

Spring Boot 支持以下嵌入式 servlet 容器:spring-doc.cadn.net.cn

名字 Servlet 版本

Tomcat 10.1 版本spring-doc.cadn.net.cn

6.0spring-doc.cadn.net.cn

Jetty 11.0spring-doc.cadn.net.cn

5.0spring-doc.cadn.net.cn

暗流 2.3spring-doc.cadn.net.cn

6.0spring-doc.cadn.net.cn

您还可以将 Spring Boot 应用程序部署到任何与 servlet 5.0+ 兼容的容器。spring-doc.cadn.net.cn

2.2. GraalVM 原生镜像

Spring Boot 应用程序可以使用 GraalVM 22.3 或更高版本转换为本机映像spring-doc.cadn.net.cn

可以使用本机构建工具 Gradle/Maven 插件或native-image工具。 您还可以使用 native-image Paketo buildpack 创建原生镜像。spring-doc.cadn.net.cn

支持以下版本:spring-doc.cadn.net.cn

名字 版本

GraalVM 社区spring-doc.cadn.net.cn

22.3spring-doc.cadn.net.cn

原生构建工具spring-doc.cadn.net.cn

0.9.28spring-doc.cadn.net.cn

3. 安装 Spring Boot

Spring Boot 可以与“经典”Java 开发工具一起使用,也可以作为命令行工具安装。 无论哪种方式,您都需要 Java SDK v17 或更高版本。 在开始之前,您应该使用以下命令检查当前的 Java 安装:spring-doc.cadn.net.cn

$ java -version

如果您不熟悉 Java 开发,或者想尝试 Spring Boot,则可能需要先尝试 Spring Boot CLI(命令行界面)。 否则,请继续阅读 “经典” 安装说明。spring-doc.cadn.net.cn

3.1. Java 开发人员的安装说明

您可以像使用任何标准 Java 库一样使用 Spring Boot。 为此,请包含适当的spring-boot-*.jar文件。 Spring Boot 不需要任何特殊的工具集成,因此您可以使用任何 IDE 或文本编辑器。 此外,Spring Boot 应用程序没有什么特别之处,因此您可以像运行任何其他 Java 程序一样运行和调试 Spring Boot 应用程序。spring-doc.cadn.net.cn

尽管您可以复制 Spring Boot jar,但我们通常建议您使用支持依赖项管理的构建工具(例如 Maven 或 Gradle)。spring-doc.cadn.net.cn

3.1.1. Maven 安装

Spring Boot 与 Apache Maven 3.5 或更高版本兼容。 如果您尚未安装 Maven,则可以按照 maven.apache.org 中的说明进行作。spring-doc.cadn.net.cn

在许多作系统上,Maven 可以与包管理器一起安装。 如果您使用的是 OSX Homebrew,请尝试brew install maven. Ubuntu 用户可以运行sudo apt-get install maven. 使用 Chocolatey 的 Windows 用户可以运行choco install maven从提升的 (管理员) 提示符。

Spring Boot 依赖项使用org.springframework.boot组 ID。 通常,您的 Maven POM 文件继承自spring-boot-starter-parentproject 并声明对一个或多个 “Starters” 的依赖关系。 Spring Boot 还提供了一个可选的 Maven 插件来创建可执行 jar。spring-doc.cadn.net.cn

有关 Spring Boot 和 Maven 入门的更多详细信息,请参阅 Maven 插件参考指南的入门部分spring-doc.cadn.net.cn

3.1.2. Gradle 安装

Spring Boot 与 Gradle 7.x(7.5 或更高版本)和 8.x 兼容。 如果您尚未安装 Gradle,可以按照 gradle.org 中的说明进行作。spring-doc.cadn.net.cn

Spring Boot 依赖项可以使用org.springframework.boot group. 通常,您的项目会声明对一个或多个 “Starters” 的依赖关系。 Spring Boot 提供了一个有用的 Gradle 插件,可用于简化依赖项声明和创建可执行 jar。spring-doc.cadn.net.cn

Gradle 包装器

当您需要构建项目时,Gradle Wrapper 提供了一种 “获取” Gradle 的好方法。 它是一个小型脚本和库,您可以将其与代码一起提交,以引导构建过程。 有关详细信息,请参阅 docs.gradle.org/current/userguide/gradle_wrapper.htmlspring-doc.cadn.net.cn

有关 Spring Boot 和 Gradle 入门的更多详细信息,请参阅 Gradle 插件参考指南的入门部分spring-doc.cadn.net.cn

3.2. 安装 Spring Boot CLI

Spring Boot CLI(命令行界面)是一个命令行工具,可用于快速使用 Spring 进行原型设计。spring-doc.cadn.net.cn

您不需要使用 CLI 来使用 Spring Boot,但这是在没有 IDE 的情况下启动 Spring 应用程序的快速方法。spring-doc.cadn.net.cn

3.2.1. 手动安装

您可以从以下位置之一下载 Spring CLI 发行版:spring-doc.cadn.net.cn

下载后,请按照解压后的存档中的INSTALL.txt说明进行作。 总之,有一个spring脚本 (spring.batfor Windows)bin/目录中的.zip文件。 或者,您可以使用java -jar使用.jar文件(该脚本可帮助您确保 Classpath 设置正确)。spring-doc.cadn.net.cn

3.2.2. 使用 SDKMAN 安装!

开发人!(软件开发工具包管理器)可用于管理各种二进制 SDK 的多个版本,包括 Groovy 和 Spring Boot CLI。 获取 SDKMAN!sdkman.io 并使用以下命令安装 Spring Boot:spring-doc.cadn.net.cn

$ sdk install springboot
$ spring --version
Spring CLI v3.0.13

如果您为 CLI 开发功能并希望访问您构建的版本,请使用以下命令:spring-doc.cadn.net.cn

$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-3.0.13-bin/spring-3.0.13/
$ sdk default springboot dev
$ spring --version
Spring CLI v3.0.13

上述说明安装spring称为dev实例。 它指向您的目标构建位置,因此每次您重新构建 Spring Boot 时,spring是最新的。spring-doc.cadn.net.cn

您可以通过运行以下命令来查看它:spring-doc.cadn.net.cn

$ sdk ls springboot

================================================================================
Available Springboot Versions
================================================================================
> + dev
* 3.0.13

================================================================================
+ - local version
* - installed
> - currently in use
================================================================================

3.2.3. OSX Homebrew 安装

如果您使用的是 Mac 并使用 Homebrew,则可以使用以下命令安装 Spring Boot CLI:spring-doc.cadn.net.cn

$ brew tap spring-io/tap
$ brew install spring-boot

Homebrew 安装spring/usr/local/bin.spring-doc.cadn.net.cn

如果您没有看到公式,则您的 brew 安装可能已过期。 在这种情况下,请运行brew update然后重试。

3.2.4. MacPorts 安装

如果您使用的是 Mac 并使用 MacPorts,则可以使用以下命令安装 Spring Boot CLI:spring-doc.cadn.net.cn

$ sudo port install spring-boot-cli

3.2.5. 命令行补全

Spring Boot CLI 包括为 BASHzsh shell 提供命令完成的脚本。 您可以source脚本(也称为spring) 放在任何 shell 中,或者将其放在您个人或系统范围的 bash 完成初始化中。 在 Debian 系统上,系统范围的脚本位于<installation location>/shell-completion/bash并且该目录中的所有脚本都会在新 shell 启动时执行。 例如,如果已使用 SDKMAN! 进行安装,要手动运行脚本,请使用以下命令:spring-doc.cadn.net.cn

$ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring
$ spring <HIT TAB HERE>
  grab  help  jar  run  test  version
如果使用 Homebrew 或 MacPorts 安装 Spring Boot CLI,则命令行完成脚本会自动注册到 shell。

3.2.6. Windows Scoop 安装

如果您使用的是 Windows 并使用 Scoop,则可以使用以下命令安装 Spring Boot CLI:spring-doc.cadn.net.cn

> scoop bucket add extras
> scoop install springboot

独家安装次数spring~/scoop/apps/springboot/current/bin.spring-doc.cadn.net.cn

如果您没有看到应用程序清单,则您的 scoop 安装可能已过期。 在这种情况下,请运行scoop update然后重试。

4. 开发您的第一个 Spring Boot 应用程序

本节介绍如何开发一个小型的 “Hello World!” Web 应用程序,其中重点介绍了 Spring Boot 的一些关键功能。 我们使用 Maven 来构建这个项目,因为大多数 IDE 都支持它。spring-doc.cadn.net.cn

spring.io Web 站点包含许多使用 Spring Boot 的“入门”指南。 如果您需要解决特定问题,请先检查那里。spring-doc.cadn.net.cn

您可以通过转到 start.spring.io 并从依赖项搜索器中选择 “Web” Starters来简化以下步骤。 这样做会生成一个新的项目结构,以便您可以立即开始编码。 有关更多详细信息,请查看 start.spring.io 用户指南spring-doc.cadn.net.cn

在开始之前,请打开终端并运行以下命令,以确保您安装了有效版本的 Java 和 Maven:spring-doc.cadn.net.cn

$ java -version
openjdk version "17.0.4.1" 2022-08-12 LTS
OpenJDK Runtime Environment (build 17.0.4.1+1-LTS)
OpenJDK 64-Bit Server VM (build 17.0.4.1+1-LTS, mixed mode, sharing)
$ mvn -v
Apache Maven 3.8.5 (3599d3414f046de2324203b78ddcf9b5e4388aa0)
Maven home: usr/Users/developer/tools/maven/3.8.5
Java version: 17.0.4.1, vendor: BellSoft, runtime: /Users/developer/sdkman/candidates/java/17.0.4.1-librca
此示例需要在其自己的目录中创建。 后续说明假定您已创建合适的目录,并且它是您的当前目录。

4.1. 创建 POM

我们需要从创建一个 Maven 开始pom.xml文件。 这pom.xml是用于构建项目的配方。 打开您最喜欢的文本编辑器并添加以下内容:spring-doc.cadn.net.cn

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.13</version>
    </parent>

    <!-- Additional lines to be added here... -->

</project>

前面的清单应该为您提供一个有效的版本。 您可以通过运行mvn package(现在,您可以忽略 “jar will be empty - no content was marked for inclusion!” 警告)。spring-doc.cadn.net.cn

此时,您可以将项目导入到 IDE 中(大多数现代 Java IDE 都包含对 Maven 的内置支持)。 为简单起见,我们在此示例中继续使用纯文本编辑器。

4.2. 添加 Classpath 依赖项

Spring Boot 提供了许多“Starters”,允许您将 jar 添加到 Classpath 中。 我们的冒烟测试应用程序使用spring-boot-starter-parentparent部分。 这spring-boot-starter-parent是一个特殊的Starters,它提供有用的 Maven 默认值。 它还提供了一个dependency-management部分,以便您可以省略version标记中。spring-doc.cadn.net.cn

其他 “Starters” 提供您在开发特定类型的应用程序时可能需要的依赖项。 由于我们正在开发一个 Web 应用程序,因此我们添加了一个spring-boot-starter-webDependency。 在此之前,我们可以通过运行以下命令来查看我们当前拥有的内容:spring-doc.cadn.net.cn

$ mvn dependency:tree

[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT

mvn dependency:treecommand 打印项目依赖项的树表示形式。 你可以看到spring-boot-starter-parent本身不提供任何依赖项。 要添加必要的依赖项,请编辑pom.xml并添加spring-boot-starter-web依赖项紧邻parent部分:spring-doc.cadn.net.cn

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

如果您运行mvn dependency:tree同样,您会看到现在还有许多额外的依赖项,包括 Tomcat Web 服务器和 Spring Boot 本身。spring-doc.cadn.net.cn

4.3. 编写代码

要完成我们的应用程序,我们需要创建一个 Java 文件。 默认情况下,Maven 编译来自src/main/java,因此您需要创建该目录结构,然后添加一个名为src/main/java/MyApplication.java以包含以下代码:spring-doc.cadn.net.cn

Java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class MyApplication {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}
Kotlin
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@SpringBootApplication
class MyApplication {

    @RequestMapping("/")
    fun home() = "Hello World!"

}

fun main(args: Array<String>) {
    runApplication<MyApplication>(*args)
}

Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections.spring-doc.cadn.net.cn

4.3.1. The @RestController and @RequestMapping Annotations

The first annotation on our MyApplication class is @RestController. This is known as a stereotype annotation. It provides hints for people reading the code and for Spring that the class plays a specific role. In this case, our class is a web @Controller, so Spring considers it when handling incoming web requests.spring-doc.cadn.net.cn

The @RequestMapping annotation provides “routing” information. It tells Spring that any HTTP request with the / path should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.spring-doc.cadn.net.cn

The @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific to Spring Boot). See the MVC section in the Spring Reference Documentation for more details.

4.3.2. The @SpringBootApplication Annotation

The second class-level annotation is @SpringBootApplication. This annotation is known as a meta-annotation, it combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan.spring-doc.cadn.net.cn

Of those, the annotation we’re most interested in here is @EnableAutoConfiguration. @EnableAutoConfiguration tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.spring-doc.cadn.net.cn

Starters and Auto-configuration

Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick and choose jar dependencies outside of the starters. Spring Boot still does its best to auto-configure your application.spring-doc.cadn.net.cn

4.3.3. The “main” Method

The final part of our application is the main method. This is a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server. We need to pass MyApplication.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.spring-doc.cadn.net.cn

4.4. Running the Example

At this point, your application should work. Since you used the spring-boot-starter-parent POM, you have a useful run goal that you can use to start the application. Type mvn spring-boot:run from the root project directory to start the application. You should see output similar to the following:spring-doc.cadn.net.cn

$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v3.0.13)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 0.906 seconds (process running for 6.514)

If you open a web browser to localhost:8080, you should see the following output:spring-doc.cadn.net.cn

Hello World!

To gracefully exit the application, press ctrl-c.spring-doc.cadn.net.cn

4.5. Creating an Executable Jar

We finish our example by creating a completely self-contained executable jar file that we could run in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.spring-doc.cadn.net.cn

Executable jars and Java

Java does not provide a standard way to load nested jar files (jar files that are themselves contained within a jar). This can be problematic if you are looking to distribute a self-contained application.spring-doc.cadn.net.cn

To solve this problem, many developers use “uber” jars. An uber jar packages all the classes from all the application’s dependencies into a single archive. The problem with this approach is that it becomes hard to see which libraries are in your application. It can also be problematic if the same filename is used (but with different content) in multiple jars.spring-doc.cadn.net.cn

Spring Boot takes a different approach and lets you actually nest jars directly.spring-doc.cadn.net.cn

To create an executable jar, we need to add the spring-boot-maven-plugin to our pom.xml. To do so, insert the following lines just below the dependencies section:spring-doc.cadn.net.cn

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
The spring-boot-starter-parent POM includes <executions> configuration to bind the repackage goal. If you do not use the parent POM, you need to declare this configuration yourself. See the plugin documentation for details.

Save your pom.xml and run mvn package from the command line, as follows:spring-doc.cadn.net.cn

$ mvn package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:3.0.13:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

If you look in the target directory, you should see myproject-0.0.1-SNAPSHOT.jar. The file should be around 18 MB in size. If you want to peek inside, you can use jar tvf, as follows:spring-doc.cadn.net.cn

$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar

You should also see a much smaller file named myproject-0.0.1-SNAPSHOT.jar.original in the target directory. This is the original jar file that Maven created before it was repackaged by Spring Boot.spring-doc.cadn.net.cn

To run that application, use the java -jar command, as follows:spring-doc.cadn.net.cn

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v3.0.13)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.536 seconds (process running for 2.864)

As before, to exit the application, press ctrl-c.spring-doc.cadn.net.cn

5. What to Read Next

Hopefully, this section provided some of the Spring Boot basics and got you on your way to writing your own applications. If you are a task-oriented type of developer, you might want to jump over to spring.io and follow some of the getting started guides that solve specific “How do I do that with Spring?” problems. We also have Spring Boot-specific “How-to” reference documentation.spring-doc.cadn.net.cn

Otherwise, the next logical step is to read using.html. If you are really impatient, you could also jump ahead and read about Spring Boot features.spring-doc.cadn.net.cn