• SpringBoot整合Swagger3.0


    1. 简介
    官网:https://swagger.io/

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

    Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。

    Swagger 的优势

    支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
    提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

    2. 集成swagger
    SpringBoot2.6.5 + Swagger3.0
    (1)导入相关依赖
    通过在项目中引入 Springfox,可以扫描相关的代码,生成该描述文件,进而生成与代码一致的接口文档和客户端代码。

    <!-- swagger -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-spring-web</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    (2)编写配置文件
    在这里插入图片描述
    这个时候 Swagger 已经算是整合到项目之中了,可以启动下服务,
    输入:http://localhost:8080/swagger-ui/index.html 即可查看 swagger 文档。

    注意:如果是swagger3.0之前的版本,需要输入:http://localhost:8080/swagger-ui.html访问。

    (3)配置config

    /**
    * 展示 controller 包下所有的接口
    */
    @Bean
    public Docket docket1() {
       // 创建一个 swagger 的 bean 实例
       return new Docket(DocumentationType.SWAGGER_2)
               .groupName("demo") // 修改组名为 "demo"
               // 配置接口信息
               .select() // 设置扫描接口
               // 配置如何扫描接口
               .apis(RequestHandlerSelectors
                       .withClassAnnotation(RestController.class)
               )
               .paths(PathSelectors
                       .any() // 满足条件的路径,该断言总为true
               )
               .build();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    /**
    * 展示路径为 /error 的所有接口(基础接口)
    */
    @Bean
    public Docket docket2() {
       // 设置请求头
       List<Parameter> parameters = new ArrayList<>();
       parameters.add(new ParameterBuilder()
               .name("token") // 字段名
               .description("token") // 描述
               .modelRef(new ModelRef("string")) // 数据类型
               .parameterType("header") // 参数类型
               .defaultValue("default value") // 默认值:可自己设置
               .hidden(true) // 是否隐藏
               .required(false) // 是否必须
               .build());
       // 创建一个 swagger 的 bean 实例
       return new Docket(DocumentationType.SWAGGER_2)
               .groupName("error") // 修改组名为 "yank"
               // 配置接口信息
               .select() // 设置扫描接口
               // 配置如何扫描接口
               .apis(RequestHandlerSelectors
                       .any() // 扫描全部的接口,默认
               )
               .paths(PathSelectors
                       .ant("/error") // 满足字符串表达式路径
               )
               .build()
               // 添加请求头参数
               .globalOperationParameters(parameters);
    }
    
    • 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
    /**
    * swagger 配置
    * @param environment 环境
    */
    @Bean
    public Docket docket(Environment environment) {
    
       // 设置环境范围
       Profiles profiles = Profiles.of("dev","test");
       // 如果在该环境返回内则返回:true,反之返回 false
       boolean flag = environment.acceptsProfiles(profiles);
    
       // 创建一个 swagger 的 bean 实例
       return new Docket(DocumentationType.SWAGGER_2)
               .enable(flag) // 是否开启 swagger:true -> 开启,false -> 关闭
               ;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3. Swagger注解详解
    (1)@Api 作用在类上,用来指定类的描述文字。

    @Api(tags = "TestController测试")
    @RestController
    public class TestController {
        ....
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (2)@ApiOperation 作用在方法上,用来对接口中具体方法做描述。

    @ApiOperation(value = "接口总体描述",notes = "<span style='color:red;'>详细描述:</span>&nbsp;方法详细描述信息")
    @GetMapping("/")
    public String login(String... index) {
        return "Hello login ~";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (3)@ApiImplicitParams 作用在方法上,用来对接口中参数进行说明。
    (4)@ApiImplicitParam 作用方法上,修饰接口方法里面的参。

    1. name:方法参数名称
    2. value:方法参数的描述
    3. dataType:方法参数数据类型
    4. defaultValue :方法参数默认值(给测试人员做测试用的)

    paramType :

    • 默认query:对应方式一
    • path:对应方式二
    • body:对应方式三

    方式一:url?id=1&user='qlh’后面参数

    @ApiOperation(value = "接口总体描述", notes = "<span style='color:red;'>详细描述:</span>&nbsp;方法详细描述信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", dataType = "String", defaultValue = "qlh"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", defaultValue = "123")
    })
    @PostMapping("/")
    public String login(String username, String password) {
        return "Hello login ~";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    方式二:url/1/2路径后 传参 在路径中获取参数

    @ApiOperation(value = "接口总体描述", notes = "<span style='color:red;'>详细描述:</span>&nbsp;方法详细描述信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", defaultValue = "qlh",paramType = "path"),
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", defaultValue = "123",paramType = "path")
    })
    @PostMapping("/index/{id}/{name}")
    public String index(@PathVariable("id") String id, @PathVariable("name") String name) {
        return "Hello World ~";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    方式三:在body中传参

    @ApiOperation(value = "接口总体描述", notes = "<span style='color:red;'>详细描述:</span>&nbsp;方法详细描述信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", defaultValue = "xxx", paramType = "body"),
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", defaultValue = "123", paramType = "body")
    })
    @PostMapping("/index")
    public String index(@RequestBody Map<String, Object> map) {
        return "Hello World ~";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (5)@ApiResponses 作用在接口方法上,用于接口的响应结果。

    @ApiResponse(code = 10001, message = "签名错误"),
    @ApiResponse(code = 10002, message = "sql错误"),
    @ApiResponse(code = 10003, message = "服务怠机,请稍后重试")
    
    • 1
    • 2
    • 3

    (6)@ApiIgnore 作用在类,方法,参数上;忽略类,方法,参数。(忽略的意思:在 swagger-ui.html中不显示)

    (7)@ApiModel 作用在类上,用来对实体类进行说明。

    @ApiModel(value="类名",description = "实体类描述")
    
    • 1

    (8)@ApiModelProperty 作用在类中的属性上,用来对实体类中的属性进行说明。

    @ApiModelProperty(value = "类属性描述",required = true,example = "属性举例",notes = "备注")
    
    • 1

    一个好的 swagger接口文档是很有必要的,这样就会减少前后端因为一些接口表述不清楚,导致的后端开发人员来回和前端人员交流沟通,大大的提高了开发的效率。

  • 相关阅读:
    【JavaSE】抽象类和接口
    [Python编程:从入门到实践] 变量&字符串
    配置鼠标右键edit with notepad
    PostgreSQL文本搜索(二)——表和索引
    git 缓冲区查看与设置
    发表博客的模板
    物联网AI MicroPython传感器学习 之 GC7219点阵屏驱动模块
    Redis服务
    Vue错误记录
    查看Android打包时签名文件keystore的MD5值
  • 原文地址:https://blog.csdn.net/qq_38747892/article/details/125501031