之前的文章讲解了swagger2注解的用法以及实例演示,本篇文章介绍一下如何使用swagger2导出离线版的api文档,分为两种格式一个是HTML5一个是PDF。对象属性、接口说明、测试用例都可以导出来方便开发人员很清楚的了解接口!
相关版本
-
Springboot版本:1.5.10.RELEASE
-
swagger2版本:2.6.1
-
maven版本:3.2.5
-
JDK版本:8
-
IDEA版本:2017.2.6
大家自己测试的时候如果不成功尽量和我版本保持一致。
index.adoc配置
include::{generated}/overview.adoc[]
include::{generated}/definitions.adoc[]
include::{generated}/paths.adoc[]
pom.xml配置
pom里面不比之前需要多配置一些东西,这个是大家需要注意的。
properties配置:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
<asciidoctor.input.directory>${project.basedir}/docs/asciidoc</asciidoctor.input.directory>
<generated.asciidoc.directory>${project.build.directory}/asciidoc</generated.asciidoc.directory>
<asciidoctor.html.output.directory>${project.build.directory}/asciidoc/html</asciidoctor.html.output.directory>
<asciidoctor.pdf.output.directory>${project.build.directory}/asciidoc/pdf</asciidoctor.pdf.output.directory>
</properties>
dependencies依赖配置:
<dependencies>
<!--fastjson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<!--spring-boot依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--web支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--swagger2依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!--swagger2-ui依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!--离线文档-->
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<version>1.1.2.RELEASE</version>
<scope>test</scope>
</dependency>
<!--生成静态文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-staticdocs</artifactId>
<version>2.6.1</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
</dependencies>
plugins插件配置:
<build>
<plugins>
<!--<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>-->
<!--Maven通过Maven Surefire Plugin插件执行单元测试-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<!--通过Asciidoctor使得asciidoc生成其他的文档格式,例如:PDF 或者HTML5-->
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<!--生成PDF-->
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.14</version>
</dependency>
<!-- Comment this section to use the default jruby artifact provided by the plugin -->
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
<!--文档生成配置-->
<configuration>
<sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
<sourceDocumentName>index.adoc</sourceDocumentName>
<attributes>
<doctype>book</doctype>
<toc>left</toc>
<toclevels>3</toclevels>
<numbered></numbered>
<hardbreaks></hardbreaks>
<sectlinks></sectlinks>
<sectanchors></sectanchors>
<generated>${generated.asciidoc.directory}</generated>
</attributes>
</configuration>
<!--因为每次执行只能处理一个后端,所以对于每个想要的输出类型,都是独立分开执行-->
<executions>
<!--html5-->
<execution>
<id>output-html</id>
<phase>test</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html5</backend>
<outputDirectory>${asciidoctor.html.output.directory}</outputDirectory>
</configuration>
</execution>
<!--pdf-->
<execution>
<id>output-pdf</id>
<phase>test</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>pdf</backend>
<outputDirectory>${asciidoctor.pdf.output.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Swagger2Config配置类
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.czq.offline.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档,可以导出离线的HTML和PDF文档")
.description("简单优雅的restfun风格")
// .termsOfServiceUrl("https://blog.csdn.net/moyanxiaoq")
.contact("chenzhiq")
.version("1.0")
.build();
}
}
User实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description="用户的实体对象")
public class User {
/**
*id
*/
@ApiModelProperty(value="用户id",name="id",required=true)
private String id;
/**
*名字
*/
@ApiModelProperty(value="用户名",name="name",required=true)
private String name;
/**
*年龄
*/
private Integer age;
}
UserController
@RestController
@RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "用户信息查询", description = "用户基本信息操作API", tags = "UserController", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
@ApiOperation(value = "/getUser", notes = "根据姓名查询用户信息")
@RequestMapping(value = "getUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public User getUser(@RequestParam("name") String name){
User user = new User();
user.setId("123");
user.setName(name);
user.setAge(25);
return user;
}
@ApiOperation(value = "/addUser", notes = "添加一个用户")
@RequestMapping(value = "addUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public User addUser(@RequestBody User user){
return user;
}
}
关键的Test类
@AutoConfigureMockMvc
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
@RunWith(SpringRunner.class)
@SpringBootTest
public class Swagger2OfflineApplicationTests {
private String snippetDir = "target/generated-snippets";
private String outputDir = "target/asciidoc";
@Autowired
private MockMvc mockMvc;
@After
public void Test() throws Exception {
// 得到swagger.json,写入outputDir目录中
mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON))
.andDo(SwaggerResultHandler.outputDirectory(outputDir).build())
.andExpect(status().isOk())
.andReturn();
// 读取上一步生成的swagger.json转成asciiDoc,写入到outputDir
// 这个outputDir必须和插件里面<generated></generated>标签配置一致
Swagger2MarkupConverter.from(outputDir + "/swagger.json")
.withPathsGroupedBy(GroupBy.TAGS)// 按tag排序
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)// 格式
.withExamples(snippetDir)
.build()
.intoFolder(outputDir);// 输出
}
@Test
public void Test2() throws Exception{
User user = new User();
user.setId("123");
user.setName("FLY");
user.setAge(25);
mockMvc.perform(post("/user/addUser").contentType(MediaType.APPLICATION_JSON)
.content(JSON.toJSONString(user))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andDo(MockMvcRestDocumentation.document("addUser", preprocessResponse(prettyPrint())));
}
@Test
public void TestApi() throws Exception {
mockMvc.perform(get("/user/getUser").param("name", "FLY")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(MockMvcRestDocumentation.document("getUser", preprocessResponse(prettyPrint())));
}
}
目录结构以及yml配置
测试
代码完成后就可启动项目访问:http://localhost:9999/swagger-ui.html 这个是在线的文档显示。导出离线的需要进入当前项目的根路径执行命令:mvn clean test
如果接口多的话命令会执行一会。结束后在 target/asciidoc
目录下会生成两个文件夹分别是 html
和 pdf
里面就是对应格式的离线文档了。
如果你的测试用例都写了而且可以测试通过,这个例子也将会显示在导出的离线文档里。
获取源码地址:https://github.com/moyanxiaoq/boot-demo/tree/master/swagger-offline