8.springboot使用RestDoc创建api文档

来源:互联网 发布:c stl程序员开发指南 编辑:程序博客网 时间:2024/05/19 11:38


1.建立过程

(1)pom.xml

主要是需要两个依赖

restDoc依赖生成snippets文件

mvn插件依赖将snippets文件变成http文档

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.tyf</groupId>  <artifactId>restdoc-test</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>jar</packaging>  <name>restdoc-test</name>  <url>http://maven.apache.org</url>  <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.2.RELEASE</version>        <relativePath/>   </parent>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>  <dependencies><dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter</artifactId>          </dependency>    <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>    </dependency>        <!-- restDoc --><dependency>            <groupId>org.springframework.restdocs</groupId>            <artifactId>spring-restdocs-mockmvc</artifactId>            <scope>test</scope>        </dependency><!-- restDoc -->  </dependencies>      <!-- maven插件 -->    <build>        <plugins>        <!-- mvn生成文档的插件 -->        <plugin>    <groupId>org.asciidoctor</groupId>    <artifactId>asciidoctor-maven-plugin</artifactId>    <executions>        <execution>            <id>generate-docs</id>            <phase>prepare-package</phase>            <goals>                <goal>process-asciidoc</goal>            </goals>            <configuration>                <sourceDocumentName>index.adoc</sourceDocumentName>                <backend>html</backend>                                <attributes>                <!-- 这里指定文档生成的位置/target/snippets -->                    <snippets>${project.build.directory}/snippets</snippets>                </attributes>            </configuration>        </execution>    </executions></plugin><!-- mvn生成文档的插件 -->            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build>            <repositories>        <repository>            <id>spring-milestones</id>            <name>Spring Milestones</name>            <url>https://repo.spring.io/milestone</url>            <snapshots>                <enabled>false</enabled>            </snapshots>        </repository>    </repositories>  </project>

(2)controller

package com.tyf.restdoc;import java.util.Collections;import java.util.Map;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/restDoc")public class modelController {    @GetMapping(value="/test")    @ResponseBody    public Map<String, String> test(){    //直接返回一个map    return Collections.singletonMap("message", "Hello World");    }    }


(3)app

package com.tyf.restdoc;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App {    public static void main( String[] args )    {        SpringApplication.run(App.class, args);    }    }

过程建立完毕,接下来对上述控制器的请求生成rest-api

2.testDoc是使用test测试生成sninppets文件

(1)test类

这个类要和启动类app在一个包下

package com.tyf.restdoc;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import static org.hamcrest.Matchers.containsString;import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;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.content;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringRunner.class)@WebMvcTest(modelController.class) //指定要测试的控制器@AutoConfigureRestDocs(outputDir = "target/snippets") //指定文档生成的位置public class test {    @Autowired    private MockMvc mockMvc;    @Test    public void shouldReturnDefaultMessage() throws Exception {        this.mockMvc.perform(get("/restDoc/test")).         andDo(print()).         andExpect(status().isOk()).         andExpect(content().string(containsString("Hello World"))).         andDo(document("home"));//生成http文档的位置target/snippets/home下面    }}

测试类指明要测试的控制器,指定sninppets文档的生成位置


(2)运行测试类生成sninppets文件

运行测试类控制台输出:

MockHttpServletRequest:      HTTP Method = GET      Request URI = /restDoc/test       Parameters = {}          Headers = {}Handler:             Type = com.tyf.restdoc.modelController           Method = public java.util.Map<java.lang.String, java.lang.String> com.tyf.restdoc.modelController.test()Async:    Async started = false     Async result = nullResolved Exception:             Type = nullModelAndView:        View name = null             View = null            Model = nullFlashMap:       Attributes = nullMockHttpServletResponse:           Status = 200    Error message = null          Headers = {Content-Type=[application/json;charset=UTF-8]}     Content type = application/json;charset=UTF-8             Body = {"message":"Hello World"}    Forwarded URL = null   Redirected URL = null          Cookies = []
生成下面snippets文件:



(3)使用mvn插件将上述文件生成http文档

mvn插件依赖上面指定了寻找snippets文档的位置

建立一个asciidoc/index.adoc文件:


文件内容指定request/response的snippets文档的位置(这个文件的有一定的书写规则参照其他教程)

这是使用restDoc生成的文档This is an example output for a service running at http://localhost:8080:下面是文档内容:.requestinclude::{snippets}/home/http-request.adoc[].responseinclude::{snippets}/home/http-response.adoc[]

进入项目文件夹包含pom.xml的这一层目录,使用命令mvn package,成功后在项目/target/generated-docs/index.html文件打开就是我们需要的html文档




原创粉丝点击