avatar

目录
使用Swagger2生成HTML、PDF静态文件

Swagger是一个简单但功能强大的API表达工具,它开源在Github中。

swagger2markup

swagger2markup用来将我们手写的或自动生成的swagger.yaml或swagger.json转换成漂亮的 AsciiDoc 或 Markdown 格式文件。 然后再通过asciidoctor-maven-plugin将其转换为HTML、PDF格式文档看。

具体操作或者缺少的文件,可以通过spring-swagger2markup-demo下载。

引入依赖

xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.github.swagger2markupgroupId>
<artifactId>swagger2markupartifactId>
<version>1.3.3version>
<scope>testscope>
dependency>

增加UserDo实体对象

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Data
@ApiModel(value = "user对象", description = "用户对象user")
public class UserDo {

@ApiModelProperty(value = "必须是2~5个中文汉字", required = true)
private String username;
private String password;

/**
* 不加example时,会报:java.lang.NumberFormatException: For input string: ""
* 原因是example默认是空字符串。在转换时,无法把空字符串转换成int类型。
*/
@ApiModelProperty(value = "年龄要求:18 < age < 60", example = "18")
private int age;

}

增加HelloController测试

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Created with IntelliJ IDEA.
* DateTime: 2020/5/15 11:10
*
* @author muycode
*/
@RestController
@RequestMapping("/hello")
@Api(value = "/hello", tags = "Test控制层")
public class HelloController {

@GetMapping("/sayHello1")
@ApiOperation(value = "测试无参", notes = "可以无参调用")
@ApiResponses(value = {
@ApiResponse(code = 1001, message = "通用异常"),
@ApiResponse(code = 1002, message = "没有找到要查询的数据")
})
public String sayHello1(){
return "sayHello1";
}

@GetMapping("/sayHello2")
@ApiOperation(value = "测试String类型参数", notes = "当rid不为null时,查询该实体。为null时,返回null")
@ApiResponses(value = {
@ApiResponse(code = 1001, message = "通用异常"),
@ApiResponse(code = 1002, message = "没有找到要查询的数据"),
@ApiResponse(code = 1003, message = "rid传递错误"),
@ApiResponse(code = 0, message = "根据rid返回对应的对象")
})
@ApiIgnore // 可以过滤不想要加入的Controller和方法
public Object sayHello2(@ApiParam(value = "rid是必须的", required = true) String rid) {
return "sayHello2";
}

@GetMapping("/sayHello3")
@ApiOperation(value = "测试对象类型参数", notes = "根据传递过来的对象,检查该对象里面的数据", response = UserDo.class)
@ApiResponses(value = {
@ApiResponse(code = 1001, message = "通用异常"),
@ApiResponse(code = 1002, message = "没有找到要查询的数据"),
@ApiResponse(code = 1003, message = "rid传递错误"),
@ApiResponse(code = 1004, message = "对象传递错误"),
@ApiResponse(code = 0, message = "根据rid返回对应的对象")
})
public Object sayHello3(
@ApiParam(value = "用户的实体对象") UserDo userDo) {
return "sayHello3";
}

@ApiOperation(value = "测试对象、String类型参数", notes = "根据传递过来的对象和rid,检查该对象里面的数据是否和rid匹配", response = UserDo.class)
@ApiResponses(value = {
@ApiResponse(code = 1001, message = "通用异常"),
@ApiResponse(code = 1002, message = "没有找到要查询的数据"),
@ApiResponse(code = 1003, message = "rid传递错误"),
@ApiResponse(code = 0, message = "根据rid返回对应的对象")
})
@GetMapping("/sayHello4")
public Object sayHello4(UserDo userDo, String rid) {
return "sayHello4";
}
}

增加Swagger配置文件

com.muycode.bsservice.config.swagger

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Created with IntelliJ IDEA.
* DateTime: 2020/6/2 10:00
* Swagger 配置
*
* @author muycode
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket sysApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.muycode"))
.paths(PathSelectors.any())
.build().globalOperationParameters(parameter());
}

@Bean
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户中心微服务接口")
.description("用户中心微服务的所有接口API")
.termsOfServiceUrl("")
.version("1.0.0")
.build();
}

private List parameter() {
List params = new ArrayList<>();
params.add(new ParameterBuilder().name("Authorization")
.description("Authorization Bearer token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false).build());
return params;
}
}

此时启动服务,通过http://127.0.0.1:8761/swagger-ui.html可查看API接口文档。

生成静态文件

增加index.adoc文件

src/docs/asciidoc/index.adoc

xml
1
2
3
4
include::{generated}/overview.adoc[]
include::{generated}/security.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/definitions.adoc[]

配置asciidoctor-maven-plugin插件

xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>11java.version>

<swagger2markup.version>1.3.1swagger2markup.version>
<swagger2markup.plugin.version>1.3.3swagger2markup.plugin.version>
<swagger2markup.extension.version>1.3.1swagger2markup.extension.version>

<asciidoctorj.version>1.5.5asciidoctorj.version>
<asciidoctorj.pdf.version>1.5.0-alpha.15asciidoctorj.pdf.version>
<jruby.version>9.1.8.0jruby.version>

<swagger.input>${project.basedir}/src/docs/swagger/swagger_petstore.yamlswagger.input>
<asciidoctor.input.directory>${project.basedir}/src/docs/asciidocasciidoctor.input.directory>
<generated.asciidoc.directory>${project.build.directory}/asciidocgenerated.asciidoc.directory>
<asciidoctor.html.output.directory>${project.build.directory}/asciidoc/htmlasciidoctor.html.output.directory>
<asciidoctor.pdf.output.directory>${project.build.directory}/asciidoc/pdfasciidoctor.pdf.output.directory>
properties>

<pluginRepositories>
<pluginRepository>
<id>jcenter-snapshotsid>
<name>jcentername>
<url>http://oss.jfrog.org/artifactory/oss-snapshot-local/url>
pluginRepository>
<pluginRepository>
<snapshots>
<enabled>falseenabled>
snapshots>
<id>jcenter-releasesid>
<name>jcentername>
<url>http://jcenter.bintray.comurl>
pluginRepository>
pluginRepositories>

<build>
<plugins>
<plugin>
<groupId>org.asciidoctorgroupId>
<artifactId>asciidoctor-maven-pluginartifactId>
<version>1.5.5version>

<dependencies>
<dependency>
<groupId>org.asciidoctorgroupId>
<artifactId>asciidoctorj-pdfartifactId>
<version>${asciidoctorj.pdf.version}version>
dependency>

<dependency>
<groupId>org.jrubygroupId>
<artifactId>jruby-completeartifactId>
<version>${jruby.version}version>
dependency>

<dependency>
<groupId>org.asciidoctorgroupId>
<artifactId>asciidoctorjartifactId>
<version>${asciidoctorj.version}version>
dependency>
dependencies>

<configuration>
<sourceDirectory>${asciidoctor.input.directory}sourceDirectory>
<sourceDocumentName>index.adocsourceDocumentName>
<attributes>
<doctype>bookdoctype>
<toc>lefttoc>
<toclevels>3toclevels>
<generated>${generated.asciidoc.directory}generated>
attributes>
configuration>

<executions>
<execution>
<id>output-htmlid>
<phase>generate-resourcesphase>
<goals>
<goal>process-asciidocgoal>
goals>
<configuration>
<backend>html5backend>
<outputDirectory>${asciidoctor.html.output.directory}outputDirectory>
configuration>
execution>

<execution>
<id>output-pdfid>
<phase>generate-resourcesphase>
<goals>
<goal>process-asciidocgoal>
goals>
<configuration>
<backend>pdfbackend>
<outputDirectory>${asciidoctor.pdf.output.directory}outputDirectory>


<sourceHighlighter>coderaysourceHighlighter>
<doctype>bookdoctype>
<attributes>
<toc>lefttoc>
<toclevels>3toclevels>
<generated>${generated.asciidoc.directory}generated>
<pdf-fontsdir>fontspdf-fontsdir>
<pdf-stylesdir>themespdf-stylesdir>
<pdf-style>cnpdf-style>
attributes>
configuration>
execution>
executions>
plugin>
plugins>
build>

增加Test类,用来生成adoc文件

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.muycode.test;

import com.muycode.bsservice.BsServiceApplication;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
* Created with IntelliJ IDEA.
* DateTime: 2020/6/2 18:16
* 生成 adoc 文件,为后续生成静态文件做准备
* mvn process-resources
*
* @author muycode
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BsServiceApplication.class)
public class DemoApplicationTests {

/**
* 执行完该测试方法,需要再执行
* mvn process-resources
*
* @throws Exception
*/
@Test
public void generateAsciiDocs() throws Exception {

URL remoteSwaggerFile = new URL("http://127.0.0.1:8761/v2/api-docs");
Path outputDirectory = Paths.get("target/asciidoc");

// 输出Ascii格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.build();

Swagger2MarkupConverter.from(remoteSwaggerFile)
.withConfig(config)
.build()
.toFolder(outputDirectory);
}
}

生成文件

  • 启动服务
  • 执行Test文件
  • 执行mvn process-resources会在target\asciidoc文件夹生成静态文件。

官网图片


参考文章

Swagger2Markup Documentation

使用Swagger生成RESTful API文档

文章作者: 颜不喜
文章链接: https://www.muycode.cn/article/swagger20200603.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 颜不喜
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论