Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。本文主要介绍了在 Spring Boot 添加 Swagger 支持, 生成可自动维护的 API 文档。

POM 文件

在pom.xml中加入Swagger2的依赖

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>

代码支持

其次我们需要在代码中添加支持,于 Application 同级目录添加 Swagger 配置类,类名随意,但需要增加@EnableSwagger2和@Configuration注解,如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class Swagger2 { @Bean
public Docket config() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.pxx.xxx.controller"))
.build();
}
//构建Api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Blog系统API文档")
.contact(new Contact("作者", "访问地址", "联系方式"))
.build();
}
}

通过@Configuration注解,让Spring来加载该类配置,@EnableSwagger2注解来启用Swagger2。

再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore注解的API)

PS:这里需要注意的是.apis(RequestHandlerSelectors.basePackage("com.pxx.xxx.controller")) 指定了 Swagger 的扫描包名, 假如不指定此项, 在 Spring Boot 项目中, 会生成 base-err-controller 的 api 接口项。

访问地址

Ok. 接下来运行项目, 访问 http://项目启动地址/v2/api-docs , 就可以访问到生成的文档的json结构. (如下图 )

具体结构可参阅 Swagger官方示例

Swagger UI地址: 访问 http://项目启动地址//swagger-ui.html

注解

OK. 现在所有工作基本就绪,通过添加相应注解就可以快速生成相关接口文档, 这也是个人认为比较好的一点。

这里开始编写自己的RESTful Controller,跟正常开发没什么区别。主要是接口方法上面新增了几个注解:

  • 通过@ApiOperation注解来给API增加说明
  • 通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明
  • 通过@ApiIgnore来忽略那些不想让生成RESTful API文档的接口
@Api(description = "文章操作相关接口")
@RestController
@RequestMapping("/article")
public class ArticleController {
private final Logger logger = LoggerFactory.getLogger(ArticleController.class); @Autowired
private BlogService blogService; @Autowired
private JsonMapper jsonMapper; @Autowired
private Environment env; @Autowired
private PxxHttp pxxHttp; @ApiOperation(value="创建文章", notes="")
@RequestMapping(value = {"/create"} , method = RequestMethod.POST)
MessageModel create(@ApiParam @RequestParam("params") String params) throws IOException { return result;
} @ApiOperation(value="更新文章", notes="")
@RequestMapping(value = "/update", method = RequestMethod.POST)
public @ResponseBody
MessageModel update(@ApiParam @RequestParam("params") String params) throws Exception { return result;
} @ApiOperation(value="mns更新文章", notes="")
@RequestMapping(value = "/updatearticle", method = RequestMethod.POST)
public @ResponseBody
MessageModel updateArticle(@ApiParam @RequestParam("params") String params) throws Exception { return result;
} }
  • @Api(description = "") : 对整个 Controller 的定义做一个解释
  • @ApiOperation(value="", notes="") : 对 Controller 内 function 定义的内容作一解释
  • @ApiParam : 添加到参数前, Swagger 会自动生成 API 文档中对参数的标示

 demo:
   Swagger2: 
package com.osp.ethscan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; /**
*
* @author zhangmingcheng
* @date 2018年9月25日
*/
@Configuration
@EnableSwagger2
public class Swagger2 { @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.osp.ethscan.controller")).paths(PathSelectors.any())
.build();
} /**
* 构建Api文档的详细信息函数
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("osp-etherscan api文档")
.description("简单优雅的restful风格,https://www.cnblogs.com/zhangmingcheng")
.contact(new Contact("zmcheng", "", ""))
.termsOfServiceUrl("https://www.cnblogs.com/zhangmingcheng").version("1.0").build();
}
}

   Controller: 

package com.osp.ethscan.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.osp.ethscan.entity.UserEntity;
import com.osp.ethscan.mapper.UserMapper;
import com.osp.ethscan.service.MailService; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore; @Api(description = "springboot学习测试相关接口")
@RestController
@RequestMapping(value = "/books")
public class UserController { @Autowired
private UserMapper userMapper; @Autowired
private MailService mailService; @ApiOperation(value = "获取用户列表", notes = "")
@RequestMapping(value = "/getUsers", method = { RequestMethod.GET })
public List<UserEntity> getUsers() {
List<UserEntity> users = userMapper.getAll();
mailService.sendSimpleMail("18753377530@163.com", "test simple mail", " hello this is simple mail");
return users;
} // 如果请求参数在url上,@ApiImplicitParam上加paramType = "path"
@RequestMapping(value = "/{id}", method = { RequestMethod.GET })
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
@ApiOperation(value = "获取用户信息", notes = "根据url的id来获取用户信息")
public UserEntity getUser(@PathVariable Long id) {
UserEntity user = userMapper.getOne(id);
return user;
} @RequestMapping("/add")
public void save(UserEntity user) {
userMapper.insert(user);
} @ApiIgnore // 使用该注解忽略这个API
@RequestMapping(value = "update")
public void update(UserEntity user) {
userMapper.update(user);
} @ApiIgnore // 使用该注解忽略这个API
@RequestMapping(value = "/delete/{id}")
public void delete(@PathVariable("id") Long id) {
userMapper.delete(id);
} }

Swagger2 生成 Spring Boot API 文档的更多相关文章

  1. Swagger2生成后台的API文档

    添加依赖: <!--Swagger2API生成--> <dependency> <groupId>io.springfox</groupId> < ...

  2. SpringBoot入门教程(二十)Swagger2-自动生成RESTful规范API文档

    Swagger2 方式,一定会让你有不一样的开发体验:功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能:及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档 ...

  3. Spring Boot 2.x基础教程:使用Swagger2构建强大的API文档

    随着前后端分离架构和微服务架构的流行,我们使用Spring Boot来构建RESTful API项目的场景越来越多.通常我们的一个RESTful API就有可能要服务于多个不同的开发人员或开发团队:I ...

  4. 使用apidoc 生成Restful web Api文档——新手问题与解决方法

    使用apidoc工具来给项目做接口文档,不仅有合理的源码注释,还可以生成对应的文档.是给源码写备注的一个极佳实践. 工具名称:apiDoc Git地址:https://github.com/apido ...

  5. apidoc 生成Restful web Api文档

    在服务器项目开发过程中,总会牵扯到接口文档的设计与编写,之前使用的都是office写一个文档,不够直观.下面介绍一种工具生成Apidoc.,该工具是Nodejs的模块,请务必在使用前安装好nodejs ...

  6. 使用apidoc 生成Restful web Api文档

    在项目开发过程中,总会牵扯到接口文档的设计与编写,之前使用的都是office工具,写一个文档,总也是不够漂亮和直观.好在git上的开源大神提供了生成文档的工具,so来介绍一下! 该工具是Nodejs的 ...

  7. Api文档生成工具与Api文档的传播(pdf)

    点击查看apidoc生成文档demo 1 环境和工具 win10 apidoc:注释生成api文档 wkhtmltopdf:apidoc生成的是html,不适合传播,于是通过wkhtmltopdf将h ...

  8. spring boot:swagger3文档展示分页和分栏的列表数据(swagger 3.0.0 / spring boot 2.3.3)

    一,什么情况下需要展示分页和分栏的数据的文档? 分页时,页面上展示的是同一类型的列表的数据,如图: 分栏时,每行都是一个列表,而且展示的数据类型也可能不同 这也是两种常用的数据返回形式 说明:刘宏缔的 ...

  9. SpringBoot中使用springfox+swagger2书写API文档

    随着前后端的分离,借口文档变的尤其重要,springfox是通过注解的形式自动生成API文档,利用它,可以很方便的书写restful API,swagger主要用于展示springfox生成的API文 ...

随机推荐

  1. mysqlbinlog基于某个偏移量进行数据的恢复(重做),--start-position,--stop-position的使用方法

    需求描述: 今天在看mysqlbinlog的内容,看到了--start-position和--stop-position这些选项, 就测试下这个参数具体该怎么进行使用呢,在此记录下. 操作过程: 1. ...

  2. 使用tensorflow深度学习识别验证码

    除了传统的PIL包处理图片,然后用pytessert+OCR识别意外,还可以使用tessorflow训练来识别验证码. 此篇代码大部分是转载的,只改了很少地方. 代码是运行在linux环境,tesso ...

  3. C# Smtp方式发送邮件

    //简单邮件传输协议类             System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();        ...

  4. ASIHttpRequest封装

    ASIHttpRequest是一个非常好的库,只是直接使用稍嫌麻烦,以下就尝试来封装一下吧. 思路:每次请求时,须要创建一个ASIHttpRequest对象,设置它的属性(url,delegate.p ...

  5. 测试用例和BUG描述规范

    欢迎关注我的公众号,了解更多的测试知识:[软件测试经验与教训] 一一BUG描述基础知识 Bug标题中需包含Bug的具体位置并以[]标注 举例:[模块-子模块-页面]XXXXXXXXXXXX Bug标题 ...

  6. Python3 抓取豆瓣电影Top250

    利用 requests 抓取豆瓣电影 Top 250: import re import requests def main(url): global num headers = {"Use ...

  7. ios 读取各种类型文件

    1.如何读取UTF-8编码的文本文件? 2.如何读取GB2312(中文)的文本文件? 3.如何读取其它编码文件? 首先解决第一个问题, 1.如何读取UTF-8编码的文本文件? NSString *fi ...

  8. Visual Studio 2013 如何在停止调试Web程序后阻止IIS Express关闭

    vs2013 调试项目的时候,当停止调试的时候,端口就被断了.之前以为是IIS那边的控制问题,但是其他并行的项目运行都没有出现这种情况. 最初也没在意,直到现在实在忍受不了了,每次重开也太烦了.就去各 ...

  9. Objective-c为什么要有属性

    属性:为什么要有属性 . 首先是因为实例变量的安全性和继承能力,如果我们允许被继承,子类要动这些实例变量,我们需要能够参与进来,如果子类设置了某个值,我们需要检查范围,保证不会破坏父类,保证不会破坏父 ...

  10. poj_1190 树状数组

    题目大意 给定一个S*S的矩形,该矩形由S*S个1x1的单元格构成,每个单元格内可以放一个整数,每次有如下可能操作: (1)改变某个单位单元格中的数的大小 (2)查询由若干个连续单元格构成的X*Y的大 ...