Spring Boot中使用Swagger

1. 启用Swagger
1.1 启用注解扫描和文档接口

直接在POM文件引入依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
1.2 启动swagger-ui

目前看到的选项有2个:

  • swaager-ui ,访问地址: http://127.0.0.1:18080/swagger-ui.html
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
  • swagger-bootstrap-ui ,也叫knife4j ,访问地址: http://127.0.0.1:18080/doc.html
    <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>${lastVersion}</version>
    </dependency>

我更喜欢swagger-bootstrap-ui的风格

1.3 创建Swagger配置类
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {

        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
    //                .apis(RequestHandlerSelectors.any())
                    .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                    .paths(PathSelectors.any())
                    .build();
        }

        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("标题lws") //标题
                    .description("简介lws") //简介
                    .termsOfServiceUrl("服务条款lws") //服务条款
                    .contact(new Contact("randy", "", "randy@gmail.com"))
                    .version("1.0.lws") //版本
                    .build();
        }
    }

在这里插入图片描述

2. 注解
2.1 @Api

@Api注解在Controller上,通过tags指定指定名称(左侧菜单的名称),tags可以指定多个值,多种使用场景通过指定相同的tag值将所有的API分组在一起。

@Api还有valuedescription属性,description已经@Deprecatedvalue号称会被当成tags值,实际测试下来无效

    @RestController
    @RequestMapping("/v1")
    @Api(tags = {"测试Swagger的注解使用"})
    public class HelloworldController {
    }

在这里插入图片描述

2.2 @ApiOperation

@ApiOperation用于注解到Controller上的方法,对应一个对外提供的接口。目前有4个属性:

属性描述
value对操作的简单说明
notes对操作的详细说明
httpMethodHTTP请求类型,可选:GET HEAD POST PUT DELETE OPTIONS PATCH
codeHTTP状态码,默认为200
produces输出的Content-Type
consumes输入的Content-Type

示例

    @RequestMapping("say")
    @ApiOperation(value = "用于打印用户输入信息", notes = "这是个什么鬼啊啊啊", httpMethod = "GET")
    public String say(@RequestParam("message") String message) {
        return message;
    }

在这里插入图片描述

2.3 @ApiParam
属性描述
name参数名称,因此这个一般应该是字母
value参数说明
defaultValue参数默认值
required参数是否必须

参数类型会通过反射获取,如果参数是基本类型会显示在数据类型字段,如果参数是自定义的类,会同时显示在数据类型schema字段

2.3.1 示例: query param

基本上只有value字段对接收说明有意义, example字段是在页面上调试给的示例值

@RequestMapping("say")
@ApiOperation(value = "用于打印用户输入信息", notes = "这是个什么鬼啊啊啊", httpMethod = "GET")
public String say(@ApiParam(value = "参数描述", example = "10086") @RequestParam("message") Integer message) {
    return "";
}

在这里插入图片描述

2.3.2 示例: 使用请求体,并用一个对象接收参数

使用@RequestBody的场景下,指定@ApiParam唯一有用的属性的value,指定其他参数没有效果

    @PostMapping("say2")
    @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
    public String say2(@ApiParam(value = "参数描述") @RequestBody ApFissionLog apFissionLog) {
        return "";
    }

在这里插入图片描述

2.4 @ApiImplicitParams 和 @ApiImplicitParam

@ApiParam相同作用,但是不把注解混合到代码内部,可读性更强,个人更喜欢这种方式

    @PostMapping("say3")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cavatar",value = "value1",example = "10001", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "cnickname",value = "value2",example = "example2", dataType = "string", paramType = "query")
    })
    public String say3(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
        return "";
    }

在这里插入图片描述

2.5 @ApiResponse

定义接口的返回值,示例中say4say5方法的表现基本一致,没发现注解的特殊意义

属性描述
codeHTTP状态码
message状态码的文本描述
response返回值的class
responseContainer返回容器类型时使用,有效值: List Set Map
    @PostMapping("say4")
    public ApFissionLog say4(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
        return new ApFissionLog();
    }

    @PostMapping("say5")
    @ApiResponse(code = 200,message = "返回描述", response = ApFissionLog.class)
    public ApFissionLog say5(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
        return new ApFissionLog();
    }
2.6 @ApiModel和@ApiModelProperty

当请求和响应是POJO的时候特别有用,现实场景中这又是最常用的情况。

@ApiModel用于指定POJO类的描述,提供更可读的类型名称(这个个人觉得没用,直接展示现有类名挺好)。

属性描述
valuemodel的别名,默认为类名
descriptionmodel的详细描述

@ApiModelProperty用于描述POJO里的字段

属性描述
value属性简短描述
example属性的示例值
required是否为必须值
    @PostMapping("say6")
    @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
    public ApFissionLog say6(@RequestBody ApFissionLog apFissionLog) {
        return new ApFissionLog();
    }

通过在ApFissionLog类上添加注解


@ApiModel(value = "model类名字", description = "描述信息")
public class ApFissionLog {

    @ApiModelProperty(value = "C用户的昵称", notes = "notes", example = "AAA-BBB-CCC", required = true)
    private String cnickname;
    @ApiModelProperty(value = "C用户的头像", notes = "notes", example = "http://www.aaa.com/avtar.png", required = true)
    private String cavatar;

}

在这里插入图片描述

3. API分组

通过在Swagger的配置类里创建两个Docket对象,扫描不同的包就能完成分组

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean("defaultApi")
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组1")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean("groupApi")
    public Docket createGroupApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组2")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题lws") //标题
                .description("简介lws") //简介
                .termsOfServiceUrl("服务条款lws") //服务条款
                .contact(new Contact("randy", "", "randy@gmail.com"))
                .version("1.0.lws") //版本
                .build();
    }
}

在这里插入图片描述

4. 完整示例
4.1 pom.xml 添加依赖
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>

    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>swagger-bootstrap-ui</artifactId>
        <version>1.9.6</version>
    </dependency>
4.2 Swagger Config 类
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean("defaultApi")
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组1")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean("groupApi")
    public Docket createGroupApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组2")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题lws") //标题
                .description("简介lws") //简介
                .termsOfServiceUrl("服务条款lws") //服务条款
                .contact(new Contact("randy", "", "randy@gmail.com"))
                .version("1.0.lws") //版本
                .build();
    }
}

4.3 Controller类
    @RestController
    @RequestMapping("/v1")
    @Api(tags = {"测试Swagger的注解使用"})
    public class HelloworldController {


        @RequestMapping("say1")
        @ApiOperation(value = "用于打印用户输入信息", notes = "这是个什么鬼啊啊啊", httpMethod = "GET")
        public String say1(@ApiParam(value = "参数描述", example = "10086") @RequestParam("message") Integer message) {
            return "";
        }

        @PostMapping("say2")
        @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
        public String say2(@ApiParam(value = "参数描述") @RequestBody ApFissionLog apFissionLog) {
            return "";
        }

        @PostMapping("say3")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "cavatar",value = "value1",example = "10001", dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "cnickname",value = "value2",example = "example2", dataType = "string", paramType = "query")
        })
        public String say3(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
            return "";
        }

        @PostMapping("say4")
        public ApFissionLog say4(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
            return new ApFissionLog();
        }

        @PostMapping("say5")
        @ApiResponse(code = 200,message = "返回描述", response = ApFissionLog.class)
        public ApFissionLog say5(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
            return new ApFissionLog();
        }

        @PostMapping("say6")
        @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
        public ApFissionLog say6(@RequestBody ApFissionLog apFissionLog) {
            return new ApFissionLog();
        }


    }
4.4 POJO类
    @Data
    @ApiModel(value = "model类名字", description = "描述信息")
    public class ApFissionLog {

        @ApiModelProperty(value = "C用户的昵称", notes = "notes", example = "AAA-BBB-CCC", required = true)
        private String cnickname;
        @ApiModelProperty(value = "C用户的头像", notes = "notes", example = "http://www.aaa.com/avtar.png", required = true)
        private String cavatar;

    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/231743.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

系统设计-微服务架构

典型的微服务架构图 下图展示了一个典型的微服务架构。 负载均衡器&#xff1a;它将传入流量分配到多个后端服务。CDN&#xff08;内容交付网络&#xff09;&#xff1a;CDN 是一组地理上分布的服务器&#xff0c;用于保存静态内容以实现更快的交付。客户端首先在 CDN 中查找内…

ElementUI 时间选择器如何限定选择时间

DatePicker 日期选择器 | Element Plus 我们如何限定我们的选择时间呢&#xff0c;比如限定选择时间为今天之前&#xff0c;或者今天之后的时间&#xff1f; 我们可以使用官方提供的disabled-date来实现 我们通过这个属性 做一个回调函数&#xff0c;在里面比较我们想要限定的时…

《数据库系统概论》学习笔记——王珊 萨师煊

第一章 绪论 一、数据库系统概述 1.数据库的4个基本概念 &#xff08;1&#xff09;数据 描述事物的符号记录称为数据 &#xff08;2&#xff09;数据库 存放数据的仓库 &#xff08;3&#xff09;数据库管理系统 主要功能&#xff1a; &#xff08;1&#xff09;数据定…

【QED】井字棋

目录 题目背景题目描述输入格式输出格式测试样例 思路核心代码 题目背景 井字棋&#xff0c;英文名叫Tic-Tac-Toe&#xff0c;是一种在 3 3 3 \times 3 33格子上进行的连珠游戏&#xff0c;和五子棋类似。游戏时&#xff0c;由分别代表O和X的两名玩家轮流在棋盘格子里留下棋子…

【恋上数据结构】前缀树 Tire 学习笔记

Tire 需求分析 如何判断一堆不重复的字符串是否以某个前缀开头&#xff1f; 用 Set\Map 存储字符串&#xff08;不重复&#xff09;遍历所有字符串进行判断缺点&#xff1a;时间复杂度 O(n) 有没有更优的数据结构实现前缀搜索&#xff1f; Tire&#xff08;和 Tree 同音&a…

快速整合EasyExcel实现Excel的上传下载

1.EasyExcel 2.Excel的上传&#xff08;读Excel&#xff09; 3.Excel的下载&#xff08;写Excel&#xff09; 4.结语 1.EasyExcel 首先&#xff0c;这里给出EasyExcel的官方文档&#xff1a;https://easyexcel.opensource.alibaba.com/ alibaba.com不用我多说了吧&#xff0c;大…

2023-12-05 Qt学习总结2

点击 <C 语言编程核心突破> 快速C语言入门 Qt学习总结 前言五 Hello Qt!六 Qt控件和事件七 Qt信号和槽八 Qt自定义信号和槽总结 前言 要解决问题: 学习qt最核心知识, 多一个都不学. 五 Hello Qt! 现在我们已经有了一个空窗口工程, 传统上, 我们要实现一个"Hello …

HXDSP2441-Demo板

板卡图示 下图为HXDSP2441DEMO板&#xff0c;HXDSP2441DEMO板是围绕HXDSP2441构建的芯片演示验证平台。 板卡简介 除了为HXDSP2441芯片提供供电、时钟、储存、网络及调试电路&#xff0c;来实现芯片最基本的功能&#xff0c;也添加了相关模块以搭建HXDSP2441的典型应用场景…

活久见—当设置不同坐标系统时,ArcMap中的图形相关位置关系会变化

这两天一件十分神奇的事情发生了&#xff1a;当设置不同坐标系统时&#xff0c;ArcMap中的图形相对位置关系会变化。 事情起因是这样的&#xff1a;博主和同行用ArcMap同时验证2个相邻多边形的相对位置关系&#xff0c;见下图图1和图2的多边形&#xff0c;在博主的ArcMap中&am…

快速登录界面关于如何登录以及多账号列表解析以及config配置文件如何读取以及JsLogin模块与SdoLogin模块如何通信(4)

1、### Jslogin模块与前端以及JsLogin模块与Sdologin的交互 配置文件的读取: <CompanyIdForQq value"301"/> <CompanyIdForWx value"300"/><CompanyIdForWb value"302"/><qq value"https://graph.qq.com/oauth2.0/au…

爱智EdgerOS之深入解析如何应用爱智的视频流模块完成拉流

一、ONVIF 规范和常见视频流传输协议 ① ONVIF 规范 随着视频监控产业链的成熟&#xff0c;市面上陆陆续续出现了各式各样的网络摄像设备&#xff0c;这些设备都需要通讯协议才能进行数据传输。早期厂商都采用私有协议&#xff0c;但是现在厂商分工明确&#xff0c;有的负责生…

计算机毕业设计springboot+ssm停车场车位预约系统java

管理员不可以注册账号 停车位包括车位所在楼层、车位编号、车位类型(全时间开放/高峰期开放)、预定状态等 用户预约时要求支付预约时间段的停车费用 违规行为&#xff1a;1.停车超过预约时间段 2.预约未使用 于系统的基本要求 &#xff08;1&#xff09;功能要求&am…

【go-zero】go-zero使用ent框架 如何使用源生sql完成查询

背景 本篇教程我们采用的是go-zero的快速脚手架工具 simple-admin 框架的开发 github地址:https://github.com/suyuan32/simple-admin-core 因为框架推荐使用Ent 这篇教程我们则对Ent的基本使用的几种形式进行一个总结 一、开启ent的源生sql 1、simple-admin生成rpc 【go-…

BUUCTF [CISCN2019 华北赛区 Day2 Web1]Hack World 1(SQL注入之布尔盲注)

题目环境判断注入类型 1 2 3 1’ 输入1’报错提示bool(false) 可知是字符型的布尔注入&#xff08;盲注&#xff09; 尝试万能密码 1’ or ‘1’1 已检测SQL注入 猜测某些关键字或者字符被过滤 FUZZ字典爆破 可以看到部分关键字被过滤&#xff0c;包括空格 All You Want Is In …

[面试题~Docker] 云原生必问基础篇

文章目录 基础相关1. Docker 是什么&#xff1f;2. 镜像是什么3. 容器是什么4. 数据卷是什么5. Docker 和虚拟机的区别&#xff1f;6. Docker 常用命令有哪些&#xff1f; 原理相关1. docker 有几种网络模式host 模式container模式none模式bridge模式 2. docker 网络实现在Linu…

AWTK 串口屏开发(1) - Hello World

1. 功能 这个例子很简单&#xff0c;制作一个调节温度的界面。在这里例子中&#xff0c;模型&#xff08;也就是数据&#xff09;里只有一个温度变量&#xff1a; 变量名数据类型功能说明温度整数温度。范围 (0-100) 摄氏度 2. 创建项目 从模板创建项目&#xff0c;将 hmi/…

物奇平台CLI MIC切换对应ADC关系

是否需要申请加入数字音频系统研究开发交流答疑群(课题组)&#xff1f;可加我微信hezkz17, 本群提供音频技术答疑服务&#xff0c;群赠送语音信号处理降噪算法&#xff0c;蓝牙耳机音频&#xff0c;DSP音频项目核心开发资料, 物奇平台CLI MIC切换对应ADC关系 1 发送CLI指令…

tqdm详细教程,实现tqdm进度条完美设计;解决进度条多行一直刷新的问题;如何使得滚动条不上下滚动(保持一行内滚动)

一、tqdm简介 tqdm是一个python进度条库&#xff0c;可以在 Python长循环中添加一个进度提示信息。 二、3种使用方法 1.tqdm(range)-自动更新 import time from tqdm import range# 自动更新 for i in tqdm(range(10)): # 共可以更新10次进度条time. Sleep(0.5) # 每次更新间…

leetcode系列:反转链表的形象表示

反转链表是一道比较简单的题&#xff0c;主要考察的是对链表数据结构的理解和双指针应用&#xff0c;比较容易出错的地方是指针的移动顺序。在练习的过程中想到了一个比较形象的表示方法&#xff0c;于是记录下来。 # Definition for singly-linked list. # class ListNode: #…

高效便捷的淘宝商品详情关键词搜索API接口

联讯数据可以介绍一些高效便捷的淘宝商品详情关键词搜索API接口。 以下是一些可以考虑使用的API接口&#xff1a; 阿里云搜索引擎API&#xff1a;阿里云搜索引擎API是一个基于云计算技术的搜索引擎&#xff0c;提供商品详情关键词搜索功能。它支持中文搜索&#xff0c;并且具…