使用 Spring Boot 构建应用

本指南提供了关于 Spring Boot 如何帮助您加速应用开发的一些示例。随着您阅读更多 Spring 入门指南,您将看到 Spring Boot 的更多用例。本指南旨在让您快速了解 Spring Boot。如果您想创建自己的基于 Spring Boot 的项目,请访问 Spring Initializr,填写您的项目详细信息,选择您的选项,然后下载打包好的 ZIP 文件。

您将构建什么

您将使用 Spring Boot 构建一个简单的 Web 应用,并向其添加一些有用的服务。

您需要什么

如何完成本指南

与大多数 Spring 入门指南一样,您可以从头开始并完成每个步骤,也可以跳过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到可工作的代码。

从头开始,请继续阅读 从 Spring Initializr 开始

跳过基础部分,请执行以下操作

完成后,您可以将结果与 gs-spring-boot/complete 中的代码进行对照。

了解 Spring Boot 的能力

Spring Boot 提供了一种快速构建应用的方式。它查看您的 classpath 和您配置的 bean,对您缺失的部分做出合理的假设,并添加这些项。使用 Spring Boot,您可以更专注于业务功能,而无需过多关注基础设施。

以下示例展示了 Spring Boot 能为您做什么

  • Spring MVC 在 classpath 中吗?有几个特定的 bean 您几乎总是需要,Spring Boot 会自动添加它们。Spring MVC 应用也需要一个 servlet 容器,因此 Spring Boot 会自动配置嵌入式 Tomcat。

  • Jetty 在 classpath 中吗?如果是,您可能不想要 Tomcat,而是想要嵌入式 Jetty。Spring Boot 会为您处理好这一点。

  • Thymeleaf 在 classpath 中吗?如果是,有几个 bean 必须始终添加到您的应用上下文中。Spring Boot 会为您添加它们。

这些只是 Spring Boot 提供自动配置的一些示例。同时,Spring Boot 不会妨碍您。例如,如果 Thymeleaf 在您的路径中,Spring Boot 会自动向您的应用上下文添加一个 SpringTemplateEngine。但是,如果您使用自己的设置定义了自己的 SpringTemplateEngine,Spring Boot 则不会添加。这让您只需少量努力即可保持控制。

Spring Boot 不生成代码,也不修改您的文件。相反,当您启动应用时,Spring Boot 会动态地连接 bean 和设置,并将它们应用到您的应用上下文中。

从 Spring Initializr 开始

您可以使用这个 预先初始化的项目,然后点击 Generate 下载一个 ZIP 文件。这个项目已配置好以适配本教程中的示例。

手动初始化项目

  1. 导航到 https://start.spring.io。这个服务会拉取您构建应用所需的所有依赖项,并为您完成大部分设置。

  2. 选择 Gradle 或 Maven,以及您想要使用的语言。本指南假设您选择了 Java。

  3. 点击 Dependencies(依赖),然后选择 Spring Web

  4. 点击 Generate(生成)。

  5. 下载生成的 ZIP 文件,这是一个根据您的选择配置好的 Web 应用的存档。

如果您的 IDE 集成了 Spring Initializr,您可以在 IDE 中完成此过程。
您也可以从 Github Fork 该项目并在您的 IDE 或其他编辑器中打开。
对于 Spring 3.0,无论您是否使用 Spring Initializr,都需要 Java 17 或更高版本。

创建一个简单的 Web 应用

现在您可以为简单的 Web 应用创建一个 Web 控制器,如以下列表所示(来自 src/main/java/com/example/springboot/HelloController.java

package com.example.springboot;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@GetMapping("/")
	public String index() {
		return "Greetings from Spring Boot!";
	}

}

该类被标记为 @RestController,这意味着它已准备好供 Spring MVC 处理 Web 请求。@GetMapping/ 映射到 index() 方法。当从浏览器或通过命令行使用 curl 调用时,该方法返回纯文本。这是因为 @RestController 结合了 @Controller@ResponseBody,这两个注解使得 Web 请求返回数据而不是视图。

创建一个 Application 类

Spring Initializr 为您创建了一个简单的应用类。然而,在这个例子中,它过于简单。您需要修改应用类以匹配以下列表(来自 src/main/java/com/example/springboot/Application.java

package com.example.springboot;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

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

	@Bean
	public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
		return args -> {

			System.out.println("Let's inspect the beans provided by Spring Boot:");

			String[] beanNames = ctx.getBeanDefinitionNames();
			Arrays.sort(beanNames);
			for (String beanName : beanNames) {
				System.out.println(beanName);
			}

		};
	}

}

@SpringBootApplication 是一个方便的注解,它添加了以下所有功能

  • @Configuration:将该类标记为应用上下文的 bean 定义源。

  • @EnableAutoConfiguration:告诉 Spring Boot 根据 classpath 设置、其他 bean 和各种属性设置开始添加 bean。例如,如果 spring-webmvc 在 classpath 中,这个注解会将应用标记为 Web 应用并激活关键行为,例如设置 DispatcherServlet

  • @ComponentScan:告诉 Spring 在 com/example 包中查找其他组件、配置和服务,以便找到控制器。

main() 方法使用 Spring Boot 的 SpringApplication.run() 方法来启动应用。您注意到没有一行 XML 吗?也没有 web.xml 文件。这个 Web 应用是 100% 纯 Java 的,您无需处理任何底层或基础设施的配置。

还有一个被标记为 @BeanCommandLineRunner 方法,它在启动时运行。它会检索您的应用创建的所有 bean 或由 Spring Boot 自动添加的 bean。它将它们排序并打印出来。

运行应用

要运行应用,请在终端窗口(在 complete 目录下)运行以下命令

./gradlew bootRun

如果您使用 Maven,请在终端窗口(在 complete 目录下)运行以下命令

./mvnw spring-boot:run

您应该会看到类似以下的输出

Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping

您可以清楚地看到 org.springframework.boot.autoconfigure bean。还有一个 tomcatEmbeddedServletContainerFactory

现在使用 curl 运行服务(在另一个终端窗口中),运行以下命令(及其输出)

$ curl http://localhost:8080
Greetings from Spring Boot!

添加单元测试

您需要为您添加的端点添加测试,Spring Test 为此提供了一些机制。

如果您使用 Gradle,请将以下依赖项添加到您的 build.gradle 文件中

testImplementation('org.springframework.boot:spring-boot-starter-test')

如果您使用 Maven,请将以下内容添加到您的 pom.xml 文件中

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

现在编写一个简单的单元测试,通过您的端点模拟 servlet 请求和响应,如以下列表所示(来自 src/test/java/com/example/springboot/HelloControllerTest.java

package com.example.springboot;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getHello() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk())
				.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
	}
}

MockMvc 来自 Spring Test,它允许您通过一组便捷的构建器类向 DispatcherServlet 发送 HTTP 请求并对结果进行断言。请注意使用 @AutoConfigureMockMvc@SpringBootTest 来注入 MockMvc 实例。使用了 @SpringBootTest,我们要求创建整个应用上下文。另一种选择是使用 @WebMvcTest 要求 Spring Boot 只创建上下文的 Web 层。无论哪种情况,Spring Boot 都会自动尝试定位应用的主应用类,但如果您想构建不同的东西,可以覆盖或缩小范围。

除了模拟 HTTP 请求生命周期外,您还可以使用 Spring Boot 编写一个简单的全栈集成测试。例如,除了(或代替)前面展示的模拟测试,我们可以创建以下测试(来自 src/test/java/com/example/springboot/HelloControllerITest.java

package com.example.springboot;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerITest {

	@Autowired
	private TestRestTemplate template;

    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity("/", String.class);
        assertThat(response.getBody()).isEqualTo("Greetings from Spring Boot!");
    }
}

由于设置了 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,嵌入式服务器会在一个随机端口上启动,实际端口会自动配置到 TestRestTemplate 的基础 URL 中。

添加生产级服务

如果您正在为您的业务构建一个网站,您可能需要添加一些管理服务。Spring Boot 通过其 actuator 模块提供了几种此类服务(例如健康检查、审计、bean 等)。

如果您使用 Gradle,请将以下依赖项添加到您的 build.gradle 文件中

implementation 'org.springframework.boot:spring-boot-starter-actuator'

如果您使用 Maven,请将以下依赖项添加到您的 pom.xml 文件中

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

然后重新启动应用。如果您使用 Gradle,请在终端窗口(在 complete 目录下)运行以下命令

./gradlew bootRun

如果您使用 Maven,请在终端窗口(在 complete 目录下)运行以下命令

./mvnw spring-boot:run

您应该会看到应用中添加了一组新的 RESTful 端点。这些是 Spring Boot 提供的管理服务。以下列表显示了典型的输出

management.endpoint.configprops-org.springframework.boot.actuate.autoconfigure.context.properties.ConfigurationPropertiesReportEndpointProperties
management.endpoint.env-org.springframework.boot.actuate.autoconfigure.env.EnvironmentEndpointProperties
management.endpoint.health-org.springframework.boot.actuate.autoconfigure.health.HealthEndpointProperties
management.endpoint.logfile-org.springframework.boot.actuate.autoconfigure.logging.LogFileWebEndpointProperties
management.endpoints.jmx-org.springframework.boot.actuate.autoconfigure.endpoint.jmx.JmxEndpointProperties
management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties
management.endpoints.web.cors-org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties
management.health.diskspace-org.springframework.boot.actuate.autoconfigure.system.DiskSpaceHealthIndicatorProperties
management.info-org.springframework.boot.actuate.autoconfigure.info.InfoContributorProperties
management.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties
management.metrics.export.simple-org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleProperties
management.server-org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties

Actuator 暴露了以下端点

还有一个 /actuator/shutdown 端点,但默认情况下只能通过 JMX 访问。要 将其启用为 HTTP 端点,请将 management.endpoint.shutdown.enabled=true 添加到您的 application.properties 文件中,并通过 management.endpoints.web.exposure.include=health,info,shutdown 来暴露它。但是,您不应为公开的应用启用 shutdown 端点。

您可以通过运行以下命令来检查应用的健康状况

$ curl http://localhost:8080/actuator/health
{"status":"UP"}

您也可以尝试通过 curl 调用 shutdown,看看如果您没有将必要的行(如前面的注释所示)添加到 application.properties 会发生什么

$ curl -X POST http://localhost:8080/actuator/shutdown
{"timestamp":1401820343710,"error":"Not Found","status":404,"message":"","path":"/actuator/shutdown"}

因为我们没有启用它,所以请求的端点不可用(因为该端点不存在)。

有关这些 REST 端点以及如何在 application.properties 文件(位于 src/main/resources 中)中调整其设置的更多详细信息,请参阅 端点文档

查看 Spring Boot 的 Starter

JAR 支持

最后一个例子展示了 Spring Boot 如何让您连接您可能不知道自己需要的 bean。它还展示了如何开启便捷的管理服务。

然而,Spring Boot 的功能不止于此。它不仅支持传统的 WAR 文件部署,还借助 Spring Boot 的 loader 模块让您能够打包成可执行的 JAR 文件。各种指南通过 spring-boot-gradle-pluginspring-boot-maven-plugin 展示了这种双重支持。

总结

恭喜!您使用 Spring Boot 构建了一个简单的 Web 应用,并了解了它如何加快您的开发速度。您还开启了一些实用的生产服务。这只是 Spring Boot 功能的一小部分示例。更多信息请参阅 Spring Boot 在线文档

另请参阅

以下指南也可能有所帮助

想编写新的指南或为现有指南贡献内容?请查阅我们的贡献指南

所有指南的代码均采用 ASLv2 许可发布,文本内容采用 署名-禁止演绎创作共享许可 发布。

获取代码

免费

在云端工作

在 Spring Academy 的云端完成本指南。

前往 Spring 学院