引言

  在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率。

  以下列举几个手写API 文档的痛点:

  • 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
  • 接口返回结果不明确
  • 不能直接在线测试接口,通常需要使用工具,比如postman
  • 接口文档太多,不好管理

  Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。

系列文档目录

Spring Boot 项目学习 (一) 项目搭建

Spring Boot 项目学习 (二) MySql + MyBatis 注解 + 分页控件 配置

Spring Boot 项目学习 (三) Spring Boot + Redis 搭建

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

配置 Swagger

  1. 修改pom.xml文件,添加依赖

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

  2. 添加Swagger2的配置文件Swagger2Config

package com.springboot.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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class SwaggerConfig { @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.springboot.controller")) //需要注意的是这里要写入控制器所在的包
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格,https://www.cnblogs.com/jiekzou/")
.termsOfServiceUrl("https://www.cnblogs.com/jiekzou/")
.version("1.0")
.build();
}
}

  如上代码所示,通过@Configuration注解,让Spring来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2。

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

  添加文档内容

  在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。

package com.springboot.controller;

import com.github.pagehelper.PageInfo;
import com.springboot.entity.Church;
import com.springboot.service.ChurchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List; @Api(value = "团契操作controller", description = "团契相关的操作", tags = {"团契模块校验接口"})
@RestController
@RequestMapping("/church")
public class ChurchController {
@Autowired
private ChurchService churchService; @ApiOperation(value = "获取指定团契信息", notes = "根据传入标识获取详细信息")
@ApiImplicitParam(name = "churchId", value = "团契标识", required = true, dataType = "String", paramType = "path")
@RequestMapping(value = "/get/{churchId}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public String getChurch(@PathVariable String churchId) {
Church church = churchService.get(churchId);
return church.toString();
} @ApiOperation(value = "获取团契列表", notes = "获取团契列表")
@RequestMapping(value = "list", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public List<Church> list() {
return churchService.list();
} @ApiOperation(value = "分页获取团契列表", notes = "获取团契列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "第几页", required = true, dataType = "Integer", paramType = "path"),
@ApiImplicitParam(name = "pageSize", value = "每页取几条记录", required = true, dataType = "Integer", paramType = "path")
})
@RequestMapping(value = "/list/{page}/{pageSize}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public PageInfo<Church> list(@PathVariable("page") int page, @PathVariable("pageSize") int pageSize) {
return churchService.list(page, pageSize);
}
}

swagger的相关注解

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

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数

启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html,最终运行效果如下

Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档的更多相关文章

  1. Spring Boot(九)Swagger2自动生成接口文档和Mock模拟数据

    一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 问题二 ...

  2. Spring Boot Swagger2自动生成接口文档

    一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 1.问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 2 ...

  3. Spring Boot中使用Swagger2自动构建API文档

    由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...

  4. geoserver整合swagger2支持自动生成API文档

    网上各种博客都有关于swagger2集成到springmvc.springboot框架的说明,但作者在整合到geoserver中确碰到了问题,调试一番最后才解决,遂总结一下. swagger2集成只需 ...

  5. Spring集成Swagger,Java自动生成Api文档

    博主很懒... Swagger官网:http://swagger.io GitHub地址:https://github.com/swagger-api 官方注解文档:http://docs.swagg ...

  6. Spring boot 之自动生成API文档swagger2

    目前解决API的方案一般有两种 1.编写文档接口.2.利用一些现成的api系统.3.如我一般想搞点特色的就自己写个api系统:http://api.zhaobaolin.vip/ ,这个还支持多用户. ...

  7. Spring Boot 项目学习 (三) Spring Boot + Redis 搭建

    0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...

  8. Spring Boot从入门到精通(十一)集成Swagger框架,实现自动生成接口文档

    Swagger是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.Swagger 是一组开源项目,其中主要要项目如下: Swagger-tools:提供各种与S ...

  9. Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档

    前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...

随机推荐

  1. 百度之星2014复赛 - 1002 - The Query on the Tree

    先上题目: The Query on the Tree Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (J ...

  2. 于工具类中@Autowired注入为NULL的问题记录

      记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...

  3. 洛谷——P1094 纪念品分组

    https://www.luogu.org/problem/show?pid=1094#sub 题目描述 元旦快到了,校学生会让乐乐负责新年晚会的纪念品发放工作.为使得参加晚会的同学所获得 的纪念品价 ...

  4. 洛谷 P2399 non hates math

    P2399 non hates math 题目背景 non习惯将分数化成小数,但在数学中要以分数形式写,不能化成小数 因此non找到了会编程的你,帮助他将小数化回分数 题目描述 给出一个小数,将它化成 ...

  5. J - Assign the task

    J - Assign the task HDU - 3974 思路:一眼秒思路<(* ̄▽ ̄*)/ dfs序+线段树. 通过dfs序把树上问题转化成线段上的问题.然后用线段树解决.    错因:都 ...

  6. 教你高速高效接入SDK——Unity统一接入渠道SDK(Android篇)

    U8SDK的设计之初,就是为了可以支持各种游戏引擎开发的游戏,而不不过Android的原生平台.眼下一大半的手游,都是採用Unity3D和Cocos2dx开发,那么这里,我们就先来一步步给大家演示,用 ...

  7. 【c语言】 模拟实现库函数的atoi函数

    // 模拟实现库函数的atoi函数 #include <stdio.h> #include <string.h> #include <assert.h> #incl ...

  8. 单点登录 SSO 的实现原理 SESSION COOKIE Memcache

    单点登录SSO(Single Sign On)说得简单点就是在一个多系统共存的环境下,用户在一处登录后,就不用在其他系统中登录,也就是用户的一次登录能得到其他所有系统的信任.单点登录在大型网站里使用得 ...

  9. cocos2d-x 3.0游戏实例学习笔记《卡牌塔防》第0步---知识点总结&amp;效果预览&amp;设计思路

    /* 说明: **1.本次游戏实例是<cocos2d-x游戏开发之旅>上的最后一个游戏.这里用3.0重写并做下笔记 **2.我也问过木头本人啦,他说:随便写.第一别全然照搬代码:第二能够说 ...

  10. k8s traefik ingress tls

    使用下面的 openssl 命令生成 CA 证书: $ openssl req -newkey rsa:2048 -nodes -keyout tls.key -x509 -days 365 -out ...