使用Spring REST Docs 编写接口文档

2023-10-10 22:10

本文主要是介绍使用Spring REST Docs 编写接口文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • Spring REST Docs 概述
  • Spring REST Docs 与 Swagger 的区别
  • 框架搭建
  • 修改pom.xml
  • 编写测试代码
    • 编写Controller代码
    • 使用MockMvc编写测试代码
    • 编写index.adoc 代码片段
  • 昨晚边试错边学习硬是搞到凌晨3点多.......
    • 生成的代码片段存放的目录
    • target目录的结构
    • index.html存放目录
    • index.html接口页面展示
    • 引用曹雪芹的诗一首
      • 满纸荒唐言
      • 一把辛酸泪
      • 都言作者痴
      • 谁解其中味
  • 持续努力中.......努力coding.........

Spring REST Docs 概述

Spring REST Docs 是基于 jdk1.8 和SpringFramework 5.0.2及以上版本的RESTful 服务文档,Spring REST Docs是通过将手写xxx.adoc文档与使用spring-mvc-test-framework测试框架编写的测试代码片段相结合的方式,来最终生成HTML接口文档,记录RESTful服务接口文档,是半自动的。

Spring REST Docs 与 Swagger 的区别

1.swagger是在线文档(传说也可以生成离线的),Spring REST Docs是离线文档
2.swagger是自动生成的,不可修改文档格式样式,Spring REST Docs 是半自动的,生成 的HTML文档样式不满意可以自定义
3.最主要的区别:swagger是对业务代码中有入侵性的,Spring REST docs是不需要修改业务代码的,没有入侵性

框架搭建

基于Spring boot ,去htttps://start.spring.io,搜索并添加Spring REST Docs 依赖
在这里插入图片描述

修改pom.xml

当你添加好maven 依赖后,会有

<build><!--当项目没有规定目标时的默认值,项目没有报错,不用加 --><defaultGoal>compile</defaultGoal><plugins><plugin><groupId>org.asciidoctor</groupId><artifactId>asciidoctor-maven-plugin</artifactId><version>1.5.3</version><executions><execution><id>generate-docs</id><phase>prepare-package</phase><goals><goal>process-asciidoc</goal></goals><configuration><backend>html</backend><doctype>book</doctype><!--手动添加snippets 属性节点,snippets的中文意思叫片段--><attributes><!--${project.build.directory} 是固定这么写的,指示项目文件夹的target目录,generated-snippets配置生成片段的存放路径--><snippets>${project.build.directory}\generated-snippets</snippets></attributes></configuration></execution></executions><dependencies><dependency><groupId>org.springframework.restdocs</groupId><artifactId>spring-restdocs-asciidoctor</artifactId><version>2.0.3.RELEASE</version></dependency></dependencies></plugin><!-- 这个插件配置主要是将generated-docs生成的在HTML接口文档复制到项目的静态文件夹中,以便将项目打包成jar包后,能够访问生成的接口文档--><plugin><artifactId>maven-resources-plugin</artifactId><version>2.7</version><executions><execution><id>copy-resources</id><phase>prepare-package</phase><goals><goal>copy-resources</goal></goals><configuration><outputDirectory>${project.build.outputDirectory}/static/docs</outputDirectory><resources><resource><directory>${project.build.directory}/generated-docs</directory></resource></resources></configuration></execution></executions></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>

编写测试代码

编写Controller代码

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;@RestController
public class HelloController {@GetMapping("/hello")public Map hello(@RequestParam("page") String page, @RequestParam("per_page") String perPage){Map<String, String> map = new HashMap<>();map.put("hello", "true");return map;}}   

使用MockMvc编写测试代码

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
//静态导入
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.requestParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {//如果没有写,默认的输出目录也是target/generated-snippets@Rulepublic JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");private MockMvc mockMvc;@Autowiredprivate WebApplicationContext context;@Beforepublic void setUp() {this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(documentationConfiguration(this.restDocumentation)).build();}@Testpublic void contextLoads() throws Exception {this.mockMvc.perform(get("/hello?page=2&per_page=100").accept(MediaType.APPLICATION_JSON).header("Authorization", "Basic dXNlcjpzZWNyZXQ=")).andDo(print()).andExpect(status().isOk())ts.andDo(document("hello",//hello为文档的Id,在target/generated-snippets文件夹下会生成hello文件夹存放snippets片段requestHeaders(headerWithName("Authorization").description("Basic auth credentials")),requestParameters(parameterWithName("page").description("The page to retrieve"),parameterWithName("per_page").description("Entries per page"))));}

编写index.adoc 代码片段

1.首先在src/main文件夹下创建一个名称为asciidoc的文件夹,名称固定,不可变。也可以选择用File API代码创建
2.在asciidoc文件夹下,创建一个名称为index.adoc的文件,该文件名可任意
3.每一个xxx.adoc,最终都会生成xxx.html 存放在/target/generated-doc文件夹中,同时也会存放在/target/classes/static/docs文件中,以便访问
4.要熟悉asciidoctor语法才能较好的编写adoc代码片段,
官网手册链接地址:https://asciidoctor.org/docs/user-manual
其他博客asciidoctor基础语法:https://blog.csdn.net/jioujiou520/article/details/90613175
5.编写接口文档目录
使用 :toc: left 命令使目录往左边放,其中left前面有一个空格
使用**:toc-title:** xxx模块的总目录名
使用= 空格 零级目录名
使用== 空格 一级目录名
使用=== 空格 一级目录名
使用 包裹起来表示注释

= 接口文档
:author: LJH
:email: aaaa@aliyun.com
:revnumber: v1.0
:revdate: 2019-07-13
:toc: left
:toc-title: hello模块 目录== 哈哈
个发几个好几个好几个== 哈哈 2
根据根据考核接口会尽快哈{snippets} 就是我们在pom.xml配置的<snippets></snippets>标签
hello 就是我们在测试代码里写的文档Id叫hello
include::{snippets}\hello\curl-request.adoc[]
include::{snippets}\hello\httpie-request.adoc[]
include::{snippets}\hello\response-body.adoc[]
include::{snippets}\hello\request-body.adoc[].http-request
include::{snippets}\hello\http-request.adoc[]
.request-headers 请求头说明
include::{snippets}\hello\request-headers.adoc[]
.request-parameters 请求参数说明
include::{snippets}\hello\request-parameters.adoc[]
include::{snippets}\hello\http-response.adoc[]== 哈哈 3和的范德萨范德萨返回多行

昨晚边试错边学习硬是搞到凌晨3点多…

生成的代码片段存放的目录

生成的代码片段存放的目录

target目录的结构

target目录的结构

index.html存放目录

index.html存放目录
index.html存放目录

index.html接口页面展示

index.html接口页面展示
index.html接口页面展示

引用曹雪芹的诗一首

满纸荒唐言

一把辛酸泪

都言作者痴

谁解其中味

持续努力中…努力coding…

这篇关于使用Spring REST Docs 编写接口文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/183412

相关文章

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图