原文: https://howtodoinjava.com/swagger2/swagger-spring-mvc-rest-example/

如今, REST微服务势头强劲。 同时,实际的 REST 规范并未建议任何标准方法来记录我们将要公开的 REST API(例如 WSDL for SOAP)。 结果,每个人都以自己的方式记录自己的 API,从而导致通用结构中的空白,所有这些都可以轻松地遵循,理解和使用。 我们需要一个通用的模式和工具。

Swagger(得到了 Google,IBM,Microsoft 等公司的支持)完成了相同工作,以填补常见文档样式的空白。 在本教程中,我们将学习使用 Swagger 来使用 swagger2 注解来生成 REST API 文档

  1. Table of Contents
  2. What is Swagger
  3. Project Structure and Technology Stack
  4. Create REST APIs
  5. Swagger2 Configuration
  6. Swagger2 Annotations
  7. Demo

Swagger

Swagger(现为“Open API Initiative”)是一种规范和框架,用于使用所有人都可以理解的通用语言来描述 REST API。 还有其他一些流行的框架,例如 RAML,Summation 等。但是,考虑到它的功能和在开发者社区中的接受程度,Swagger 在这一点上最受欢迎。

它提供了人类可读和机器可读的文档格式。 它同时提供 JSON 和 UI 支持。 JSON 可以用作机器可读格式,Swagger-UI用于可视化显示,人类只需浏览 api 文档即可轻松理解。

项目结构与技术栈

项目的文件夹结构为:

Swagger – Spring REST 示例 - 图1

Swagger2 项目结构

在本演示中,我们将使用以下技术。

  1. Eclipse 作为 IDE
  2. Maven 作为构建工具
  3. Spring Boot 作为应用框架
  4. Spring Rest 作为 REST API 框架
  5. Swagger2 作为 REST 文档框架
  6. Java 1.8

创建 REST API

我们将首先创建一些 REST API,这些 API 将用于展示 Swagger 文档功能。 我们将使用 Spring 引导样式公开剩余的 API,以缩短开发时间。

  1. 从具有 Web,Rest Repositories,Actuator 依赖项的 Spring Boot 初始化器门户创建一个 Spring Boot 项目。 给出其他 Maven GAV 坐标并下载项目。 该屏幕如下所示:
    Swagger – Spring REST 示例 - 图2
    Spring Boot REST 项目生成
    将项目解压缩并将其作为现有的 maven 项目导入 Eclipse。 在此步骤中,将从 maven 仓库下载所有必需的依赖项。 在此步骤中执行全新的mvn clean install,以便正确下载所有与 Spring Boot 相关的工件。

  2. 打开application.properties并添加以下属性。 这将在/swagger2-demo上下文路径中启动应用。

    1. server.contextPath=/swagger2-demo
  1. 添加一个 REST 控制器“Swagger2DemoRestController”,该控制器将在“Student”实体上提供基于 REST 的基本功能。
    Swagger2DemoRestController.java ```java package com.example.springbootswagger2.controller;

import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.springbootswagger2.model.Student;

@RestController public class Swagger2DemoRestController {

  1. List<Student> students = new ArrayList<Student>();
  2. {
  3. students.add(new Student("Sajal", "IV", "India"));
  4. students.add(new Student("Lokesh", "V", "India"));
  5. students.add(new Student("Kajal", "III", "USA"));
  6. students.add(new Student("Sukesh", "VI", "USA"));
  7. }
  8. @RequestMapping(value = "/getStudents")
  9. public List<Student> getStudents() {
  10. return students;
  11. }
  12. @RequestMapping(value = "/getStudent/{name}")
  13. public Student getStudent(@PathVariable(value = "name") String name) {
  14. return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);
  15. }
  16. @RequestMapping(value = "/getStudentByCountry/{country}")
  17. public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
  18. System.out.println("Searching Student in country : " + country);
  19. List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
  20. .collect(Collectors.toList());
  21. System.out.println(studentsByCountry);
  22. return studentsByCountry;
  23. }
  24. @RequestMapping(value = "/getStudentByClass/{cls}")
  25. public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
  26. return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
  27. }

}

  1. <br />**`Student.java`**
  2. ```java
  3. package com.example.springbootswagger2.model;
  4. public class Student {
  5. private String name;
  6. private String cls;
  7. private String country;
  8. public Student(String name, String cls, String country) {
  9. super();
  10. this.name = name;
  11. this.cls = cls;
  12. this.country = country;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public String getCls() {
  18. return cls;
  19. }
  20. public String getCountry() {
  21. return country;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]";
  26. }
  27. }
  1. 作为 Spring Boot 应用启动该应用。 测试几个 REST 端点,以检查它们是否工作正常:

    • http://localhost:8080/swagger2-demo/getStudents
    • http://localhost:8080/swagger2-demo/getStudent/sajal
    • http://localhost:8080/swagger2-demo/getStudentByCountry/india
    • http://localhost:8080/swagger2-demo/getStudentByClass/v

Swagger2 配置

我们的 REST API 已准备就绪。 现在将 swagger2 支持添加到project.ff

添加 Swagger2 Maven 依赖项

打开spring-boot-swagger2项目的pom.xml文件,并在下面添加两个与 swagger 相关的依赖项,即springfox-swagger2springfox-swagger-ui

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-swagger2</artifactId>
  4. <version>2.6.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.springfox</groupId>
  8. <artifactId>springfox-swagger-ui</artifactId>
  9. <version>2.6.1</version>
  10. </dependency>

实际上,swagger API 具有多种变体,并且维护在不同的工件中。 今天,我们将使用springfox,因为该版本可以很好地适应任何基于 spring 的配置。 我们还可以轻松地尝试其他配置,并且应该提供相同的功能-无需更改/只需稍作更改即可。

添加 Swagger2 配置

在代码库中添加以下配置。 为了帮助您理解配置,我添加了嵌入式注解。

  1. package com.example.springbootswagger2.configuration;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  6. import com.google.common.base.Predicates;
  7. import springfox.documentation.builders.RequestHandlerSelectors;
  8. import springfox.documentation.spi.DocumentationType;
  9. import springfox.documentation.spring.web.plugins.Docket;
  10. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  11. @Configuration
  12. @EnableSwagger2
  13. public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter
  14. {
  15. @Bean
  16. public Docket api() {
  17. // @formatter:off
  18. //Register the controllers to swagger
  19. //Also it is configuring the Swagger Docket
  20. return new Docket(DocumentationType.SWAGGER_2).select()
  21. // .apis(RequestHandlerSelectors.any())
  22. .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
  23. // .paths(PathSelectors.any())
  24. // .paths(PathSelectors.ant("/swagger2-demo"))
  25. .build();
  26. // @formatter:on
  27. }
  28. @Override
  29. public void addResourceHandlers(ResourceHandlerRegistry registry)
  30. {
  31. //enabling swagger-ui part for visual documentation
  32. registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
  33. registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
  34. }
  35. }

验证 Swagger2 JSON 格式文档

执行 maven 并启动服务器。 打开链接http://localhost:8080/swagger2-demo/v2/api-docs,它应该以JSON格式提供整个文档。 这并不是那么容易阅读和理解,实际上 Swagger 已经提供了将其用于其他系统中的功能,例如如今流行的 API 管理工具,它提供了 API 网关,API 缓存,API 文档等功能。

Swagger – Spring REST 示例 - 图3

JSON 文档

验证 Swagger2 UI 文档

打开http://localhost:8080/swagger2-demo/swagger-ui.html在浏览器中查看 Swagger UI 文档。

Swagger – Spring REST 示例 - 图4

Swagger2 UI 文档(无注解)

Swagger2 注解

默认生成的 API 文档很好,但是缺少详细的 API 级别信息。 Swagger 提供了一些注解,可以将这些详细信息添加到 API。 例如:

  1. @Api – 我们可以将此注解添加到控制器,以添加有关控制器的基本信息。
    1. @Api(value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!")
    2. @RestController
    3. public class Swagger2DemoRestController {
    4. ...
    5. }
  1. @ApiOperation@ApiResponses – 我们可以将这些注解添加到控制器中的任何 rest 方法,以添加与该方法有关的基本信息。 例如: ```java @ApiOperation(value = “Get list of Students in the System “, response = Iterable.class, tags = “getStudents”) @ApiResponses(value = {
    1. @ApiResponse(code = 200, message = "Success|OK"),
    2. @ApiResponse(code = 401, message = "not authorized!"),
    3. @ApiResponse(code = 403, message = "forbidden!!!"),
    4. @ApiResponse(code = 404, message = "not found!!!") })

@RequestMapping(value = “/getStudents”) public List getStudents() { return students; }

  1. <br />在这里,我们可以将`tags`添加到方法中,以在`swagger-ui`中添加一些分组。
  2. 3.
  3. `@ApiModelProperty` – 在 Model 属性中使用此注解可为该 Model 属性的 Swagger 输出添加一些描述。 例如:
  4. ```java
  5. @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
  6. private String name;

添加 swagger2 注解后的控制器和模型类代码。

Swagger2DemoRestController.java

  1. package com.example.springbootswagger2.controller;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.stream.Collectors;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import com.example.springbootswagger2.model.Student;
  9. import io.swagger.annotations.Api;
  10. import io.swagger.annotations.ApiOperation;
  11. import io.swagger.annotations.ApiResponse;
  12. import io.swagger.annotations.ApiResponses;
  13. @Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!")
  14. @RestController
  15. public class Swagger2DemoRestController {
  16. List<Student> students = new ArrayList<Student>();
  17. {
  18. students.add(new Student("Sajal", "IV", "India"));
  19. students.add(new Student("Lokesh", "V", "India"));
  20. students.add(new Student("Kajal", "III", "USA"));
  21. students.add(new Student("Sukesh", "VI", "USA"));
  22. }
  23. @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
  24. @ApiResponses(value = {
  25. @ApiResponse(code = 200, message = "Suceess|OK"),
  26. @ApiResponse(code = 401, message = "not authorized!"),
  27. @ApiResponse(code = 403, message = "forbidden!!!"),
  28. @ApiResponse(code = 404, message = "not found!!!") })
  29. @RequestMapping(value = "/getStudents")
  30. public List<Student> getStudents() {
  31. return students;
  32. }
  33. @ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent")
  34. @RequestMapping(value = "/getStudent/{name}")
  35. public Student getStudent(@PathVariable(value = "name") String name) {
  36. return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);
  37. }
  38. @ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry")
  39. @RequestMapping(value = "/getStudentByCountry/{country}")
  40. public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
  41. System.out.println("Searching Student in country : " + country);
  42. List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
  43. .collect(Collectors.toList());
  44. System.out.println(studentsByCountry);
  45. return studentsByCountry;
  46. }
  47. // @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass")
  48. @RequestMapping(value = "/getStudentByClass/{cls}")
  49. public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
  50. return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
  51. }
  52. }

Student.java

  1. package com.example.springbootswagger2.model;
  2. import io.swagger.annotations.ApiModelProperty;
  3. public class Student
  4. {
  5. @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
  6. private String name;
  7. @ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class")
  8. private String cls;
  9. @ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country")
  10. private String country;
  11. public Student(String name, String cls, String country) {
  12. super();
  13. this.name = name;
  14. this.cls = cls;
  15. this.country = country;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public String getCls() {
  21. return cls;
  22. }
  23. public String getCountry() {
  24. return country;
  25. }
  26. @Override
  27. public String toString() {
  28. return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]";
  29. }
  30. }

演示

现在,在正确注解我们的 REST API 之后,我们来看一下最终输出。 打开http://localhost:8080/swagger2-demo/swagger-ui.html在浏览器中查看 Swagger ui 文档。

Swagger – Spring REST 示例 - 图5

Swagger2 REST API 最终输出

这一切都将通过 Spring Boot 应用 swagger2 创建 REST API 文档。 将我的问题放在评论部分。

下载源码

学习愉快!