综合概述

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. PHP imagecolorat - 取得某像素的颜色索引值

    imagecolorat — 取得某像素的颜色索引值.高佣联盟 www.cgewang.com 语法 int imagecolorat ( resource $image , int $x , int ...

  2. Blob分析之board.hdev

    * board.hdev: Detection of missing solder* 获取当前系统参数get_system ('clip_region', Information)*设置当前系统参数s ...

  3. loj #6247. 九个太阳 k次单位根 神仙构造 FFT求和原理

    LINK:九个太阳 不可做系列. 构造比较神仙. 考虑FFT的求和原理有 \(\frac{1}{k}\sum_{j=0}^{k-1}(w_k^j)^n=[k|n]\) 带入这道题的式子. 有\(\su ...

  4. 利用python进行数据分析PDF高清完整版免费下载|百度云盘|Python基础教程免费电子书

    点击获取提取码:hi2j 内容简介 [名人推荐] "科学计算和数据分析社区已经等待这本书很多年了:大量具体的实践建议,以及大量综合应用方法.本书在未来几年里肯定会成为Python领域中技术计 ...

  5. 【NOIP2017】跳房子 题解(单调队列优化线性DP)

    前言:把鸽了1个月的博客补上 ----------------- 题目链接 题目大意:机器人的灵敏性为$d$.每次可以花费$g$个金币来改造机器人,那么机器人向右跳的范围为$[min(d-g,1),m ...

  6. SEO(Search Engine Optimization)优化

    SEO(Search Engine Optimization)汉议为搜索引擎优化,是一种利用搜索引擎的规则提高网站在有关搜索引擎内自然排名的方式. SEO的目的是对网站进行深度的优化,从而帮助网站获取 ...

  7. spring时遇到的小问题

    最近在学习spring的时候遇到了两个小问题,在此总结一下 1.少导了所需要的包 运行测试程序,报出以下错误. 初步分析,得知是dataSource数据源没有创建成功,以为dataSource配置文件 ...

  8. Web组件的三种关联关系

    Web应用程序如此强大的原因之一是它们能彼此链接和聚合信息资源.Web组件之间存在三种关联关系: ●  请求转发 ●  URL重定向 ●  包含 存在以上关联关系的Web组件可以是JSP或Servle ...

  9. C#LeetCode刷题之#34-在排序数组中查找元素的第一个和最后一个位置(Find First and Last Position of Element in Sorted Array)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4970 访问. 给定一个按照升序排列的整数数组 nums,和一个目 ...

  10. C#LeetCode刷题之#709-转换成小写字母(To Lower Case)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3965 访问. 实现函数 ToLowerCase(),该函数接收一 ...