• SpringBoot整合Swagger2


    整合Swagger2

    1.Swagger介绍

    前后端分离开发模式中,api文档是最好的沟通方式。

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

    1、及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)

    2、规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)

    3、一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)

    4、可测性 (直接在接口文档上进行测试,以方便理解业务)

    2.集成knife4j

    文档地址:https://doc.xiaominfo.com/

    knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案。

    knife4j属于service模块公共资源,因此我们集成到service-uitl模块

    3.添加依赖

    <dependency>
        <groupId>com.github.xiaoymingroupId>
        <artifactId>knife4j-spring-boot-starterartifactId>
        <version>2.0.8version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4.添加knife4j配置类

    package com.yurui.manage_system_springboot.config;
    
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.service.Parameter;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @Author YurUi
     * @Version 1.0
     */
    /**
     * knife4j配置信息
     */
    @Configuration
    @EnableSwagger2WebMvc
    public class Knife4jConfig {
    
        @Bean
        public Docket adminApiConfig(){
            List<Parameter> pars = new ArrayList<>();
            ParameterBuilder tokenPar = new ParameterBuilder();
            tokenPar.name("token")
                    .description("用户token")
                    .defaultValue("")
                    .modelRef(new ModelRef("string"))
                    .parameterType("header")
                    .required(false)
                    .build();
            pars.add(tokenPar.build());
            //添加head参数end
    
            Docket adminApi = new Docket(DocumentationType.SWAGGER_2)
                    .groupName("adminApi")
                    .apiInfo(adminApiInfo())
                    .select()
                    //只显示admin路径下的页面
                    .apis(RequestHandlerSelectors.basePackage("com.yurui.manage_system_springboot"))
                    .paths(PathSelectors.regex("/admin/.*"))
                    .build()
                    .globalOperationParameters(pars);
            return adminApi;
        }
    
        private ApiInfo adminApiInfo(){
    
            return new ApiInfoBuilder()
                    .title("后台管理系统-API文档")
                    .description("本文档描述了后台管理系统微服务接口定义")
                    .version("1.0")
                    .contact(new Contact("yurui", "http://yurui.com", "1584841572@qq.com"))
                    .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
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    5.控制器方法

    添加相关的注解

    package com.yurui.manage_system_springboot.controller;
    
    import com.yurui.manage_system_springboot.pojo.User;
    import com.yurui.manage_system_springboot.service.UserService;
    import com.yurui.manage_system_springboot.utils.JsonResult;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * @Author YurUi
     * @Version 1.0
     */
    @RestController
    @RequestMapping("/admin/system")
    @Api(tags = "系统接口")
    public class SystemController {
    
        @Autowired
        private UserService userService;
    
        @RequestMapping("/user")
        @ApiOperation("查看所有user信息")
        public JsonResult login(){
    
            List<User> list = userService.getAllUser();
    
            return JsonResult.ok(list);
        }
    }
    
    
    • 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
    常用的注解:
    @Api(tags = "系统接口"):作用在类上,标注该类的作用
    
    @ApiOperation("查看所有user信息"):作用在方法,标注该方法的作用
    
    @ApiParam():作用在形参的位置,说明参数
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    6.测试

    http://localhost/doc.html#/home

    注意是:一定要与项目部署的端口一致

    在这里插入图片描述

    7.可能出现的BUG

    当我们按照上述的步骤整合knife4j后启动项目时,发现报以下错误原因是:空指针异常

    Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
    
    • 1

    解决方案:
    第一种:如果你使用的SpringBoot的版本是2.6.x以上版本,需要将版本降到为2.5.x版本

    第二种:如果不想修改SpringBoot的版本,需要在SpringBoot的启动类中添加一个注解@EnableWebMvc

  • 相关阅读:
    GNSS伪距从码片到米的单位转换
    玩转堆排序以及Topk问题——【数据结构】
    springboot高校考勤小程序的设计与实现毕业设计-附源码131039
    【考研】数据结构考点——归并排序
    【SysBench】Linux 安装 sysbench-1.20
    驱动初级Day03_内核模块下_参数和依赖
    JavaSE——图书管理
    2023 极术通讯-汽车“新四化”路上,需要一片安全山海
    [强网杯 2019]随便注
    【VBox】解决复制VBox虚拟机后提示硬盘UUID 已经存在的问题
  • 原文地址:https://blog.csdn.net/weixin_47267628/article/details/127952910