综合概述

spring-boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口。这些接口不但会服务于传统的web端(b/s),也会服务于移动端。在实际开发过程中,这些接口还要提供给开发测试进行相关的白盒测试,那么势必存在如何在多人协作中共享和及时更新API开发接口文档的问题。

假如你已经对传统的wiki文档共享方式所带来的弊端深恶痛绝,那么尝试一下Swagger2 方式,一定会让你有不一样的开发体验。

使用 Swagger 集成文档具有以下几个优势:

  • 功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能;
  • 及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档,省心省力;
  • 整合简单 :通过添加pom依赖和简单配置,内嵌于应用中就可同时发布API接口文档界面,不需要部署独立服务。

创建一个SpringBoot项目

从零开始的SpringBoot项目 ( 二 ) 使用IDEA创建一个SpringBoot项目

添加相关依赖

 <!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<!-- SwaggerUI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>

添加配置类 SwaggerConfig

 package com.my_springboot.config;

 import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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.EnableSwagger2; /**
* Swagger2配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer { @Bean
public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 加了ApiOperation注解的类,才会生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 指定包下的类,才生成接口文档
//.apis(RequestHandlerSelectors.basePackage("com.my_springboot.user.controller"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
//访问地址:http://localhost:8080/swagger-ui.html#/
return new ApiInfoBuilder()
.title("my_springboot后端api接口文档")// 设置页面标题
.description("欢迎访问my_springboot接口文档,本文档描述了my_springboot后端相关接口的定义")// 描述
.termsOfServiceUrl("https://服务条款.com/")// 服务条款
.contact(new Contact("联系人", null, null))// 设置联系人
.version("1.0.0")// 定义版本号
.build();
} }

添加控制器 HellowController

 package com.my_springboot.controller;

 import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; /* 类注解 */
@Api(value = "desc of class")
@RestController
public class HelloController { /* 方法注解 */
@ApiOperation(value = "desc of method", notes = "")
@GetMapping(value="/hello")
public Object hello( /* 参数注解 */ @ApiParam(value = "desc of param" , required=true ) @RequestParam String name) {
return "Hello " + name + "!";
}
}

启动项目并访问浏览器

常用注解说明

swagger 通过注解接口生成文档,包括接口名,请求方法,参数,返回信息等。

@Api: 修饰整个类,用于controller类上

@ApiOperation: 描述一个接口,用户controller方法上

@ApiParam: 单个参数描述

@ApiModel: 用来对象接收参数,即返回对象

@ApiModelProperty: 对象接收参数时,描述对象的字段

@ApiResponse: Http响应其中的描述,在ApiResonse中

@ApiResponses: Http响应所有的描述,用在

@ApiIgnore: 忽略这个API

@ApiError: 发生错误的返回信息

@ApiImplicitParam: 一个请求参数

@ApiImplicitParam: 多个请求参数

更多使用说明,参考 Swagger 使用手册

添加请求参数

在很多时候,我们需要在调用我们每一个接口的时候都携带上一些通用参数,比如采取token验证逻辑的往往在接口请求时需要把token也一起传入后台,接下来,我们就来讲解一下如何给Swagger添加固定的请求参数。

修改SwaggerConfig配置类,替换成如下内容,利用ParameterBuilder构成请求参数。

 package com.my_springboot.config;

 import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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.EnableSwagger2; /**
* Swagger2配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer { @Bean
public Docket createRestApi() { // 为swagger添加header参数可供输入
ParameterBuilder userTokenHeader = new ParameterBuilder();
userTokenHeader.name("token").description("令牌")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build();
List<Parameter> pars = new ArrayList<Parameter>();
pars.add(userTokenHeader.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 加了ApiOperation注解的类,才会生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 指定包下的类,才生成接口文档
//.apis(RequestHandlerSelectors.basePackage("com.my_springboot.user.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars);
} private ApiInfo apiInfo() {
//访问地址:http://localhost:8088/xin_mei_love/swagger-ui.html#!
return new ApiInfoBuilder()
.title("my_springboot后端api接口文档")// 设置页面标题
.description("欢迎访问my_springboot接口文档,本文档描述了my_springboot后端相关接口的定义")// 描述
.termsOfServiceUrl("https://服务条款.com/")// 服务条款
.contact(new Contact("联系人", null, null))// 设置联系人
.version("1.0.0")// 定义版本号
.build();
} }

完成之后重新启动应用,再次查看hello接口,可以看到已经支持发送token请求参数了。

从零开始的SpringBoot项目 ( 五 ) 整合 Swagger 实现在线API文档的功能的更多相关文章

  1. 从零开始的SpringBoot项目 ( 六 ) 整合 MybatisPlus 实现代码自动生成

    1.添加依赖 <!-- MySQL数据库 --> <dependency> <groupId>mysql</groupId> <artifactI ...

  2. 使用swagger实现在线api文档自动生成 在线测试api接口

    使用vs nuget包管理工具搜索Swashbuckle 然后安装便可 注释依赖于vs生成的xml注释文件

  3. Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档

    0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...

  4. Spring Boot 2.X(十五):集成 Swagger2 开发 API 文档(在线+离线)

    前言 相信很多后端开发在项目中都会碰到要写 api 文档,不管是给前端.移动端等提供更好的对接,还是以后为了以后交接方便,都会要求写 api 文档. 而手写 api 文档的话有诸多痛点: 文档更新的时 ...

  5. WebApi生成在线API文档--Swagger

    1.前言 1.1 SwaggerUI SwaggerUI 是一个简单的Restful API 测试和文档工具.简单.漂亮.易用(官方demo).通过读取JSON 配置显示API. 项目本身仅仅也只依赖 ...

  6. Swagger UI及 Swagger editor教程 API文档搭配 Node使用

    swagger ui 是一个在线文档生成和测试的利器,目前发现最好用的.为啥好用呢?打开 demo,支持API自动生成同步的在线文档些文档可用于项目内部API审核方便测试人员了解 API这些文档可作为 ...

  7. Swagger UI教程 API 文档神器 搭配Node使用

    ASP.NET Web API 使用Swagger生成在线帮助测试文档 Swagger 生成 ASP.NET Web API 前言 swagger ui是一个API在线文档生成和测试的利器,目前发现最 ...

  8. go实践之swagger自动生成api文档

    文章目录 go实践之swagger自动生成api文档 1.安装需要用到的包 2.接口代码支持swagger 3. 生成swagger接口 go实践之swagger自动生成api文档 作为一个后端开发, ...

  9. Spring Boot 集成 Swagger 生成 RESTful API 文档

    原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...

随机推荐

  1. Tkinter经典写法

    1.继承 tkinter.Frame 类,实现类的基本写法 2.创建主窗口及主窗口大小位置及标题 3.将需要添加的组件放入到类中进行创建, 继承的 Frame 类需要使用 master 参数作为父类的 ...

  2. Numpy改变数组的形状

    import numpy as np n = np.arange(10) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 查看数组的大小 n.size # # 将数 ...

  3. PHP array_intersect_ukey() 函数

    实例 比较两个数组的键名(使用用户自定义函数比较键名),并返回交集: <?phpfunction myfunction($a,$b){if ($a===$b){return 0;}return ...

  4. PHP gregoriantojd() 函数

    ------------恢复内容开始------------ 实例 把格利高里历法的日期转换为儒略日计数,然后再转换回格利高里历法的日期: <?php$jd=gregoriantojd(6,20 ...

  5. 牛客挑战赛39 D 牛牛的数学题 NTT FMT FWT

    LINK:牛牛的数学题 题目看起来很不可做的样子. 但是 不难分析一下i,j之间的关系. 对于x=i|j且i&j==0, i,j一定是x的子集 我们可以暴力枚举子集来处理x这个数组. 考虑 x ...

  6. 执行HiveSQL出现的问题

    -- ::, INFO [main] org.apache.hadoop.hive.ql.exec.ReduceSinkOperator: RECORDS_OUT_INTERMEDIATE:, -- ...

  7. python爬取高匿代理IP(再也不用担心会进小黑屋了)

    为什么要用代理IP 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却不知道如何去学习更加高深的知识.那么针对这三类人 ...

  8. Python datetime 转 JSON

    Python datetime 转 JSON Python 中将 datetime 转换为 JSON 类型,在使用 Django 时遇到的问题. 环境: Python2.7 代码: import js ...

  9. git使用-git仓库

    1.初始化版本库 git init 2.添加文件到版本库 git add git commit 3.查看仓库状态 git status 4.撤销初始化命令 rm -rf .git

  10. 03 Arduino-模拟输出与PWM的操作方法

    在arduino开发板上面,标注为PWM的管脚的可以被当作数模转换管脚使用 01 模拟输出  analogWrite(pin, value) pin: 选定的引脚号码  value:取值范围 0-25 ...