开始
1. Spring Boot 简介
Spring Boot 可帮助您创建可以运行的基于 Spring 的独立生产级应用程序。 我们对 Spring 平台和第三方库持固执己见的看法,因此您可以毫不费力地开始使用。 大多数 Spring Boot 应用程序只需要很少的 Spring 配置。
您可以使用 Spring Boot 创建可使用以下java -jar
或更传统的战争部署。
我们的主要目标是:
-
为所有 Spring 开发提供极其快速且可广泛访问的入门体验。
-
开箱即用,但当需求开始与默认值不同时,请迅速离开。
-
提供一系列大型项目通用的非功能性功能(例如嵌入式服务器、安全性、指标、运行状况检查和外部化配置)。
-
绝对不需要代码生成(当不针对本机图像时),也不需要 XML 配置。
2. 系统要求
Spring Boot 3.0.13 需要 Java 17,并且与 Java 21 兼容。还需要 Spring Framework 6.0.14 或更高版本。
为以下构建工具提供显式构建支持:
构建工具 | 版本 |
---|---|
Maven 系列 |
3.5+ |
Gradle |
7.x(7.5 或更高版本)和 8.x |
2.1. Servlet 容器
Spring Boot 支持以下嵌入式 servlet 容器:
名字 | Servlet 版本 |
---|---|
Tomcat 10.1 版本 |
6.0 |
Jetty 11.0 |
5.0 |
暗流 2.3 |
6.0 |
您还可以将 Spring Boot 应用程序部署到任何与 servlet 5.0+ 兼容的容器。
2.2. GraalVM 原生镜像
Spring Boot 应用程序可以使用 GraalVM 22.3 或更高版本转换为本机映像。
可以使用本机构建工具 Gradle/Maven 插件或native-image
工具。
您还可以使用 native-image Paketo buildpack 创建原生镜像。
支持以下版本:
名字 | 版本 |
---|---|
GraalVM 社区 |
22.3 |
原生构建工具 |
0.9.28 |
3. 安装 Spring Boot
Spring Boot 可以与“经典”Java 开发工具一起使用,也可以作为命令行工具安装。 无论哪种方式,您都需要 Java SDK v17 或更高版本。 在开始之前,您应该使用以下命令检查当前的 Java 安装:
$ java -version
如果您不熟悉 Java 开发,或者想尝试 Spring Boot,则可能需要先尝试 Spring Boot CLI(命令行界面)。 否则,请继续阅读 “经典” 安装说明。
3.1. Java 开发人员的安装说明
您可以像使用任何标准 Java 库一样使用 Spring Boot。
为此,请包含适当的spring-boot-*.jar
文件。
Spring Boot 不需要任何特殊的工具集成,因此您可以使用任何 IDE 或文本编辑器。
此外,Spring Boot 应用程序没有什么特别之处,因此您可以像运行任何其他 Java 程序一样运行和调试 Spring Boot 应用程序。
尽管您可以复制 Spring Boot jar,但我们通常建议您使用支持依赖项管理的构建工具(例如 Maven 或 Gradle)。
3.1.1. Maven 安装
Spring Boot 与 Apache Maven 3.5 或更高版本兼容。 如果您尚未安装 Maven,则可以按照 maven.apache.org 中的说明进行作。
在许多作系统上,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-parent
project 并声明对一个或多个 “Starters” 的依赖关系。
Spring Boot 还提供了一个可选的 Maven 插件来创建可执行 jar。
有关 Spring Boot 和 Maven 入门的更多详细信息,请参阅 Maven 插件参考指南的入门部分。
3.1.2. Gradle 安装
Spring Boot 与 Gradle 7.x(7.5 或更高版本)和 8.x 兼容。 如果您尚未安装 Gradle,可以按照 gradle.org 中的说明进行作。
Spring Boot 依赖项可以使用org.springframework.boot
group
.
通常,您的项目会声明对一个或多个 “Starters” 的依赖关系。
Spring Boot 提供了一个有用的 Gradle 插件,可用于简化依赖项声明和创建可执行 jar。
有关 Spring Boot 和 Gradle 入门的更多详细信息,请参阅 Gradle 插件参考指南的入门部分。
3.2. 安装 Spring Boot CLI
Spring Boot CLI(命令行界面)是一个命令行工具,可用于快速使用 Spring 进行原型设计。
您不需要使用 CLI 来使用 Spring Boot,但这是在没有 IDE 的情况下启动 Spring 应用程序的快速方法。
3.2.1. 手动安装
您可以从以下位置之一下载 Spring CLI 发行版:
下载后,请按照解压后的存档中的INSTALL.txt说明进行作。
总之,有一个spring
脚本 (spring.bat
for Windows)bin/
目录中的.zip
文件。
或者,您可以使用java -jar
使用.jar
文件(该脚本可帮助您确保 Classpath 设置正确)。
3.2.2. 使用 SDKMAN 安装!
开发人!(软件开发工具包管理器)可用于管理各种二进制 SDK 的多个版本,包括 Groovy 和 Spring Boot CLI。 获取 SDKMAN!sdkman.io 并使用以下命令安装 Spring Boot:
$ sdk install springboot
$ spring --version
Spring CLI v3.0.13
如果您为 CLI 开发功能并希望访问您构建的版本,请使用以下命令:
$ 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
是最新的。
您可以通过运行以下命令来查看它:
$ 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:
$ brew tap spring-io/tap
$ brew install spring-boot
Homebrew 安装spring
自/usr/local/bin
.
如果您没有看到公式,则您的 brew 安装可能已过期。
在这种情况下,请运行brew update 然后重试。 |
3.2.4. MacPorts 安装
如果您使用的是 Mac 并使用 MacPorts,则可以使用以下命令安装 Spring Boot CLI:
$ sudo port install spring-boot-cli
3.2.5. 命令行补全
Spring Boot CLI 包括为 BASH 和 zsh shell 提供命令完成的脚本。
您可以source
脚本(也称为spring
) 放在任何 shell 中,或者将其放在您个人或系统范围的 bash 完成初始化中。
在 Debian 系统上,系统范围的脚本位于<installation location>/shell-completion/bash
并且该目录中的所有脚本都会在新 shell 启动时执行。
例如,如果已使用 SDKMAN! 进行安装,要手动运行脚本,请使用以下命令:
$ . ~/.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:
> scoop bucket add extras > scoop install springboot
独家安装次数spring
自~/scoop/apps/springboot/current/bin
.
如果您没有看到应用程序清单,则您的 scoop 安装可能已过期。
在这种情况下,请运行scoop update 然后重试。 |
4. 开发您的第一个 Spring Boot 应用程序
本节介绍如何开发一个小型的 “Hello World!” Web 应用程序,其中重点介绍了 Spring Boot 的一些关键功能。 我们使用 Maven 来构建这个项目,因为大多数 IDE 都支持它。
您可以通过转到 start.spring.io 并从依赖项搜索器中选择 “Web” Starters来简化以下步骤。 这样做会生成一个新的项目结构,以便您可以立即开始编码。 有关更多详细信息,请查看 start.spring.io 用户指南。 |
在开始之前,请打开终端并运行以下命令,以确保您安装了有效版本的 Java 和 Maven:
$ 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
是用于构建项目的配方。
打开您最喜欢的文本编辑器并添加以下内容:
<?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!” 警告)。
此时,您可以将项目导入到 IDE 中(大多数现代 Java IDE 都包含对 Maven 的内置支持)。 为简单起见,我们在此示例中继续使用纯文本编辑器。 |
4.2. 添加 Classpath 依赖项
Spring Boot 提供了许多“Starters”,允许您将 jar 添加到 Classpath 中。
我们的冒烟测试应用程序使用spring-boot-starter-parent
在parent
部分。
这spring-boot-starter-parent
是一个特殊的Starters,它提供有用的 Maven 默认值。
它还提供了一个dependency-management
部分,以便您可以省略version
标记中。
其他 “Starters” 提供您在开发特定类型的应用程序时可能需要的依赖项。
由于我们正在开发一个 Web 应用程序,因此我们添加了一个spring-boot-starter-web
Dependency。
在此之前,我们可以通过运行以下命令来查看我们当前拥有的内容:
$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
这mvn dependency:tree
command 打印项目依赖项的树表示形式。
你可以看到spring-boot-starter-parent
本身不提供任何依赖项。
要添加必要的依赖项,请编辑pom.xml
并添加spring-boot-starter-web
依赖项紧邻parent
部分:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
如果您运行mvn dependency:tree
同样,您会看到现在还有许多额外的依赖项,包括 Tomcat Web 服务器和 Spring Boot 本身。
4.3. 编写代码
要完成我们的应用程序,我们需要创建一个 Java 文件。
默认情况下,Maven 编译来自src/main/java
,因此您需要创建该目录结构,然后添加一个名为src/main/java/MyApplication.java
以包含以下代码:
package com.example;
@RestController
@SpringBootApplication
public class MyApplication {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Kotlin
@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.
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.
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.
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
.
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.
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.
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:
$ 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:
Hello World!
To gracefully exit the application, press ctrl-c
.
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.
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:
<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:
$ 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:
$ 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.
To run that application, use the java -jar
command, as follows:
$ 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
.
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.
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.