使用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

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do