• 在 SpringBoot 项目中使用 Swagger 接口文档演示


    在 SpringBoot 项目中使用 Swagger 接口文档演示

    1. Swagger 介绍

    在一个项目开发过程中,当前端开发人员根据后端开发人员给出的 API 接口文档进行接口联调对接时,可能会出现这样的矛盾:前端开发人员抱怨后端开发人员给出的 API 接口文档和实际的情况有所出入,而后端开发人员由于繁重的开发任务已经身心俱疲,想到自己还要负责维护接口文档的任务更是不堪重负。

    这时就需要一个解决方案,希望它能够在后端开发人员进行接口开发时,能够帮助后端工程师自动生成相应的接口文档,当接口有变化时,也能够对文档进行及时更新,这样前端工程师在进行接口联调时,不会再出现发现文档和实际情况不一致的情况。

    幸运的是,伟大的开源社区就给出了这样的一套解决方案,称为 Swagger,正如它的中译一样,让后端工程师能够大摇大摆地走,以后再面对前端工程师时神奇十足哈哈!

    Swagger 是一个规范和完整的框架,它用于生成、描述、调用和可视化 RESTful 风格的 Web 服务,避免手动维护 API 文档的带来的麻烦。

    后端工程师只需要按照它的规范去定义接口及接口相关的信息,再通过 Swagger 衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多种语言的客户端和服务端的代码,以及在线接口调试页面等等。

    这样,如果按照新的开发模式,在开发新版本或者迭代版本的时候,只需要更新 Swagger 描述文件,就可以自动生成接口文档和客户端服务端代码,做到调用端代码、服务端代码以及接口文档的一致性。

    2. 使用 Swagger 接口文档框架

    为了简化 Swagger 的使用,Spring 框架对 Swagger 进行了整合,建立了 Spring-Swagger 项目,之后又更新作 Springfox. 通过在项目中引入 Springfox,可以扫描相关的代码,生成描述文件以及与代码一致的接口文档和客户端代码。

    引入 Springfox 的 maven 坐标如下

    <dependency>
    	<!--swagger 文档的 UI 组件-->
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Swagger 常用的注解及对应的描述如下表所示:

    注解描述
    @Api用在请求的类上,例如 @Controller,表示对类的说明
    @ApiModel用在类上,通常是实体类,表示一个返回响应数据的信息
    @ApiModelProperty用在属性上,描述响应类的属性
    @ApiOperation用在请求的方法上,说明方法的用途、作用
    @ApiImplicitParams用在请求的方法上,表示一组参数说明
    @ApiImplicitParam用在 @ApiImplicitParams 注解中,指定一个请求参数的各个方面

    下面就开始着手在 SpringBoot 项目中使用 Swagger 文档接口。

    第一步,创建一个名为 swagger_demo 的 maven 工程,工程的 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.hzz</groupId>
        <artifactId>swagger_demo</artifactId>
        <version>1.0-SNAPSHOT</version>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
            <relativePath/>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--swagger 文档的 UI 组件-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
        </dependencies>
    </project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    第二步,在 resources 目录下创建 application.yml 文件

    server:
      port: 9000    #指定服务端口号
    
    • 1
    • 2

    第三步,创建实体类 User 和 Menu

    User 类

    package com.hzz.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    @Data
    @ApiModel(description = "用户实体")
    public class User {
        @ApiModelProperty(value = "主键")
        private int id;
        @ApiModelProperty(value = "姓名")
        private String name;
        @ApiModelProperty(value = "年龄")
        private int age;
        @ApiModelProperty(value = "地址")
        private String address;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    Menu 类

    package com.hzz.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    @Data
    @ApiModel(description = "菜单实体")
    public class Menu {
        @ApiModelProperty(value = "主键")
        private int id;
        @ApiModelProperty(value = "菜单名称")
        private String name;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    第四步,创建 UserController 和 MenuController

    UserController 类

    package com.hzz.controller.user;
    
    import com.hzz.entity.User;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @RestController
    @RequestMapping("/user")
    @Api(tags = "用户控制器")
    public class UserController {
    
        @GetMapping("/getUsers")
        @ApiOperation(value = "查询所有用户", notes = "查询所有用户信息")
        public List<User> getAllUsers() {
            User user = new User();
            user.setId(100);
            user.setName("hzz");
            user.setAge(20);
            user.setAddress("hz");
            List<User> list = new ArrayList<>();
            list.add(user);
            return list;
        }
    
        @PostMapping("/save")
        @ApiOperation(value = "新增用户", notes = "新增用户信息")
        public String save(@RequestBody User user) {
            return "OK";
        }
    
        @PutMapping("/update")
        @ApiOperation(value = "修改用户", notes = "修改用户信息")
        public String update(@RequestBody User user) {
            return "OK";
        }
    
        @DeleteMapping("/delete")
        @ApiOperation(value = "删除用户", notes = "删除用户信息")
        public String delete(int id) {
            return "OK";
        }
    
        @ApiImplicitParams({
                @ApiImplicitParam(name = "pageNum", value = "页码",
                        required = true, type = "Integer"),
                @ApiImplicitParam(name = "pageSize", value = "每页条数",
                        required = true, type = "Integer"),
        })
        @ApiOperation(value = "分页查询用户信息")
        @GetMapping(value = "page/{pageNum}/{pageSize}")
        public String findByPage(@PathVariable Integer pageNum,
                                 @PathVariable Integer pageSize) {
            return "OK";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    MenuController 类

    package com.hzz.controller.menu;
    
    import com.hzz.entity.Menu;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @RestController
    @RequestMapping("/menu")
    @Api(tags = "菜单控制器")
    public class MenuController {
        @GetMapping("/getMenus")
        @ApiOperation(value = "查询所有菜单", notes = "查询所有菜单信息")
        public List<Menu> getMenus() {
            Menu menu = new Menu();
            menu.setId(100);
            menu.setName("hzz");
            List<Menu> list = new ArrayList<>();
            list.add(menu);
            return list;
        }
    
        @PostMapping("/save")
        @ApiOperation(value = "新增菜单", notes = "新增菜单信息")
        public String save(@RequestBody Menu menu) {
            return "OK";
        }
    
        @PutMapping("/update")
        @ApiOperation(value = "修改菜单", notes = "修改菜单信息")
        public String update(@RequestBody Menu menu) {
            return "OK";
        }
    
        @DeleteMapping("/delete")
        @ApiOperation(value = "删除菜单", notes = "删除菜单信息")
        public String delete(int id){
            return "OK";
        }
    
        @ApiImplicitParams({
                @ApiImplicitParam(name = "pageNum", value = "页码",
                        required = true, type = "Integer"),
                @ApiImplicitParam(name = "pageSize", value = "每页条数",
                        required = true, type = "Integer"),
        })
    
        @ApiOperation(value = "分页查询菜单信息")
        @GetMapping(value = "page/{pageNum}/{pageSize}")
        public String findByPage(@PathVariable Integer pageNum,
                                 @PathVariable Integer pageSize) {
            return "OK";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    第五步,创建 SwaggerAutoConfiguration 配置类

    package com.hzz.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * 自动配置类
     */
    @Configuration
    @EnableSwagger2  //启动swagger
    public class SwaggerAutoConfiguration {
        @Bean
        public Docket createRestApi1() {
            //docket 用于封装接口文档相关信息
            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .apiInfo(apiInfo()).groupName("用户接口组")
                    .select()
                    //为当前包路径
                    .apis(RequestHandlerSelectors.basePackage("com.hzz.controller.user"))
                    .build();
            return docket;
        }
    
        @Bean
        public Docket createRestApi2() {
            //docket 用于封装接口文档相关信息
            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo()).groupName("菜单接口组")
                    .select()
                    //为当前包路径
                    .apis(RequestHandlerSelectors.basePackage("com.hzz.controller.menu"))
                    .build();
            return docket;
        }
    
        //构建 API 文档的详细信息
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("API接口文档") //页面标题
                    //联系人
                    .contact(new Contact("华仔仔coding", null,null)) //url和email没有则填充null即可
                    .version("1.0")  //版本号
                    .description("API 描述")  //描述
                    .build();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    第六步,创建启动类

    package com.hzz;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SwaggerDemoApplication {
        public static void main(String[] args) {
            SpringApplication.run(SwaggerDemoApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    第七步,启动项目,访问地址 http://localhost:9000/swagger-ui.html,swagger 接口文档可视化界面如下

    在这里插入图片描述

    此外,还可以在文档中进行测试,可以点击某个请求,例如测试上图中的 DELETE 请求,点击 Try it out 进行测试接口

    在这里插入图片描述

    然后,输入请求的参数,点击 Execute 执行,便可以在 Server response 下方看到响应结果

    在这里插入图片描述

    当然,还可以测试其他的接口,观察响应数据,为了使得篇幅不那么冗长,这里就不再演示了吗,以上便是在 SpringBoot 项目中使用 Swagger 接口文档演示的整个过程。

  • 相关阅读:
    net-java-php-python-基于mvc的酒吧系统的设计与实现计算机毕业设计程序
    Java数字处理类--Math类--大数字运算
    怎么将自己的Maven项目上传到Maven中央仓库/Maven阿里云云效仓库
    常用的函数-MySQL
    mysql如何创建添加索引?
    基础知识:临界阻尼
    Unity中Shader矩阵的逆矩阵
    【FAQ】安防视频监控平台EasyNVR无法控制云台,该如何解决?
    FIORI:创建项目与部署
    RocketMQ源码分析(九)之AllocateMappedFileService
  • 原文地址:https://blog.csdn.net/weixin_43252521/article/details/125603485