发布于 2026-01-06 2 阅读
0

使用 Spring Boot 构建 REST Web 服务的简单示例;为什么选择 Spring Boot?前提条件;使用 Spring Initializr;Hello-World REST 端点;集成测试;Spring 配置;结论

使用 Spring Boot 构建 REST Web 服务的简单工作示例

为什么选择 Spring Boot?

先决条件

使用 Spring 初始化

Hello-World REST 端点

集成测试

Spring 配置

结论

本文将介绍一个能够响应HTTP 请求的非常基础的Web 服务。这篇博客非常适合想要开始使用Spring Boot 的人。

棕榈滩

为什么选择 Spring Boot?

那么,作为一名 Java 开发人员,你为什么要关注 Spring Boot 呢?原因有很多!😊 首先,Spring 是开源的,这意味着它由社区持续维护和测试,而且完全免费。其次,根据Hotframeworks 的数据,它是2019 年使用最广泛的Java Web 框架。第三,Spring Boot 提供了一种快速启动并运行Spring 应用程序的绝佳方法:有了 Spring Boot,你无需担心大量的样板代码和配置。Spring Boot 会自动为你设置许多默认配置,但你也可以根据需要随时覆盖这些默认设置。为此,Spring Boot 具有一定的“倾向性”,这意味着 Spring 团队为你选择了一些配置,而这些配置已被社区广泛接受。

顺便问一下,我们为什么要关注 Web 框架呢?因为在典型的 Web 服务中,有很多功能是反复使用的,例如响应 HTTP 请求、为每个传入请求创建新线程、HTTPS 和 OAuth2 等安全机制等等。我们不想每次创建新的 Web 服务时都重新发明轮子,因此我们可以使用Web 框架,它们提供了所有这些通用机制。Web 框架的其他功能还包括数据库访问、任务调度、控制反转等等。所有这些优秀的功能都包含在 Spring Boot 中,因此您可以有更多时间去做其他事情,比如喝一杯美味的卡布奇诺☕

最后,我想提一下,Spring 不仅与 Java 兼容,还与Kotlin兼容,Kotlin 是一种在Android 应用开发中非常流行的语言

先决条件

现在我们将创建一个“Hello World”Web服务。所有必要的代码都已在此处提供,最终解决方案也可在我的Github仓库中找到。

完成所有步骤的必要条件:

  • Maven
  • Java JDK 8 或更高版本
  • 命令行

在本博客中,我们将全部操作在命令行完成。当然,您也可以使用 IntelliJ 等集成开发环境 (IDE)。事实上,我很快会发布一篇关于 IntelliJ 的文章,介绍一些入门知识,例如代码补全、在项目中搜索特定代码片段、编译、调试等等。

使用 Spring 初始化

我们使用Maven作为构建工具,Spring Boot 提供了一种创建 POM 文件的绝佳方式:访问https://start.spring.io/并按如下方式输入我们应用程序的所有详细信息:

Spring Boot 初始化

当然,如果您愿意,可以使用更新版本的 Spring Boot 和 Java。无论如何,请记住添加“Spring Web”作为初始依赖项——我们将使用它来构建 REST 端点。填写完所有信息后,点击“生成”按钮。这将下载一个包含初始 Java 项目结构以及最重要的初始pom.xml文件的 ZIP 文件。

让我们仔细看一下生成的 POM 文件。在 POM 文件的顶部,可以看到我们继承自 ` spring-boot-starter-parentSpringBootApplication`,它包含了 Spring Boot 应用所需的所有组件。



  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>


Enter fullscreen mode Exit fullscreen mode

在 POM 文件的下方dependencies,您可以看到我们将使用spring-boot-starter-web



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


Enter fullscreen mode Exit fullscreen mode

您可以在mvnrepository.com上找到关于此依赖项的详细描述

用于构建基于 Spring MVC 的 Web 应用(包括 RESTful 应用)的入门指南。默认使用 Tomcat 作为嵌入式容器。

总之,到目前为止,我们只查看了一个重要的文件:pom.xml 文件。接下来,让我们重点关注主类,它位于src/main/java/com/example/springbootexample/SpringBootExampleApplication.java



@SpringBootApplication
public class SpringBootExampleApplication {

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

}


Enter fullscreen mode Exit fullscreen mode

这里有趣的是顶部的注解:@SpringBootApplication。除其他作用外,此注解可确保我们的 Spring Boot 应用程序配置了默认的 Spring Boot 属性(例如 HTTP 请求超时以及许多其他属性)。

Hello-World REST 端点

由于我们稍后要创建一个 REST 端点,我们需要让 Main 类搜索 Servlet,因此我们需要在 Main 类中添加另一个注解:(@ServletComponentScan再次说明,如果您今天不想写代码,可以查看我Github 仓库中的完整代码)。

接下来,我们创建一个 REST 端点。为此,我们创建一个新的 Java 类并将其命名为PingRestController.java(您可以使用与 Main 类相同的文件夹)。

内容PingRestController.java应如下所示:



package com.example.springbootexample;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PingRestController {

  @RequestMapping(method = RequestMethod.GET, path = "/api/ping")
  public ResponseEntity<String> getPing() {
    return ResponseEntity.ok("pong");
  }

}


Enter fullscreen mode Exit fullscreen mode

该注解@RestController表明此类包含 REST 端点。每个 REST 端点都是一个带有 `@RequestMapping` 注解的方法@RequestMapping。在本例中,我们只有一个这样的方法:getPing`getPing`。每当相应的 REST 调用到达我们的服务器时,都会执行此方法。让我们更详细地了解一下 `@RequestMapping` 注解:我们指定了 `RequestMapping`method和 ` pathRequestBody` 变量。这两个变量指定我们要捕获对 URI“/api/ping”的 HTTP GET 请求。此外,请注意 `getPing` 方法的返回类型:`RequestBody`ResponseEntity包装了 HTTP 响应,HTTP 请求体应该只是一个字符串。因此,HTTP 调用的响应将始终如下所示:



Headers: Status: 200, ContentType: text/plain;charset=UTF-8
Body: "pong"


Enter fullscreen mode Exit fullscreen mode

修改完 Main 类和 PingRestController 类后,我们就具备了运行服务的所有条件。在终端中输入:



mvn clean install
java -jar target/spring-boot-example-0.0.1-SNAPSHOT.jar


Enter fullscreen mode Exit fullscreen mode

现在,在您常用的网络浏览器中输入:



localhost:8080/api/ping


Enter fullscreen mode Exit fullscreen mode

你应该看看“乒乓”声!

在后台,你的浏览器会向 localhost 发送一个 HTTP GET 请求,该请求由你的 Spring Boot 应用程序处理,并以字符串“pong”作为响应。

集成测试

确保 REST 端点真正正常工作的一个好方法是编写集成测试。每次构建应用程序时,此测试都会运行。为什么要使用集成测试呢?首先,因为我们开发人员希望实现一切自动化,不喜欢手动测试。其次,因为这能增强未来开发的稳定性:随着 Web 服务的扩展,此测试仍会在每次构建时运行,从而确保该功能始终有效。

什么是集成测试?与只关注单个类的单元测试不同,集成测试针对的是整个应用程序,其中所有组件都集成在一起。我们通常会模拟第三方系统(例如数据库),以便进行独立于(有时不可靠的)外部系统的测试。在我们的例子中,我们希望真正启动 Web 服务,但如果我们有数据库,则只需模拟即可。

我们的集成测试实现如下src/test/java/com/example/springbootexample/PingIntegrationTest.java



package com.example.springbootexample;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PingIntegrationTest {

  @Autowired
  private MockMvc mvc;

  @Test
  public void testHelloWorldEndpoint() throws Exception {
    String response = mvc
        .perform(get("/api/ping"))
        .andReturn().getResponse().getContentAsString();
    assertEquals("Hello world", response);
  }
}


Enter fullscreen mode Exit fullscreen mode

如您所见,测试 REST 端点需要编写稍微多一些的代码。现在,我们先专注于关键部分,至于每一行代码的含义,就留给您自己去理解吧。以下是重点:

  • @SpringBootTest在本地启动 Web 服务器,并使其准备好响应测试 REST 调用。
  • private MockMvc mvcMockMvc 对象允许我们对 Web 服务器的 HTTP 调用进行触发测试。
  • @Test就像 JUnit 测试一样,每个测试都是在一个带有@test注解的方法中实现的。
  • mvc.perform(get(“api/ping”))这里我们触发一个 HTTP GET 请求

您可以使用以下命令运行测试:



mvn -Dtest=PingIntegrationTest test


Enter fullscreen mode Exit fullscreen mode

啊……集成测试失败了🙈 怎么回事?别担心,上面的测试用例里只是有个小错误。找出错误原因并修复它就交给你们了!

Spring 配置

Spring Boot 会自动配置服务的许多属性。例如,当我们 ping 自己的服务时,必须使用 8080 端口。我们并没有在任何地方定义它……这只是 Spring Boot 的默认设置。所有这些默认属性都可以在官方文档中找到(链接在此)。要更改此默认行为,我们只需要创建一个application.properties文件并覆盖相应的值即可。所以,请继续修改src/main/resources/application.properties



server:
  port: 8082


Enter fullscreen mode Exit fullscreen mode

现在,当您重新编译并重新启动服务时,REST 端点将在端口 8082 上可用。

结论

我们已经编写了创建简单 REST 服务所需的所有代码。使用 Spring Boot,我们只需要 23 行 Java 代码就能创建一个可用的 REST 端点!而且,完全不需要 XML 配置。真是太棒了!

希望这篇文章能帮助你入门 Spring Boot,请记得点赞❤️并在下方留言哦!😊

文章来源:https://dev.to/pmgysel/simple-working-example-of-rest-web-service-with-spring-boot-4plo