工作上前后台分离,有时候接口定义没定好导致开发阶段要修改接口,前台要接口每次都来问,想要及时改好的接口文档。两边都挺麻烦的。我项目里面使用了swagger有页面的文档,能不能生成静态文件呢?结果还真的可以,美滋滋
前言
此处从springboot引用swagger到导出一次讲解,搭建过程可能会遇见很多问题,还请根据实际情况搜索。
参考
引用pom.xml
这里需要注意一点,我现在提供的pom是可以的,如果直接使用最新的swagger包,在使用swagger上没问题,但是后面生成静态文档会有报错
错误信息如下1
java.lang.NoSuchMethodError: io.swagger.models.Response.responseSchema(Lio/swagger/models/Model;)Lio/swagger/models/Response;
意思就是方法没有,解决方法参考这篇博客。基本上的意思就是jar包版本的问题,依赖的某些包没有维护了导致的
1 | <!--swagger2--> |
编写SwaggerConfig.java
这里直接上我的代码,具体参考官网或者上网搜。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
public class SwaggerConfig {
public Docket createRestApi() {
return new Docket(DoucmentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("xxx.xxx.xxx.xxx"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("服务接口API")
.description("服务接口的文档说明")
.termsOfServiceUrl("")
.version("1.0.0")
.build();
}
}
controller接口例子
api注解是swagger的1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18"测试接口", tags = { "测试接口" }) (value =
"/demo") (
public class DemoController {
private DemoService demoService;
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
"测试接口", notes = "测试接口") (value =
"getTest/{id}") (value =
public MyResult<Demo> getDome(@PathVariable("id") String id) {
return demoService.getDemo(id);
}
...
...
}
到这一步启动项目,没报错的话浏览器输入localhost:8080/swagger-ui.html
就可以看到swagger 的页面文档,还可以进行接口测试。
生成静态文档
静态文档的生成,写测试用例就行,也不一定是测试用例,如果你愿意再写个main方法或者写在功能代码里的话。
SwaggerStaticDocTest.java1
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138 (SpringRunner.class)
(classes = SwaggerTestApplication.class, webEnvironment = RANDOM_PORT)
public class SwaggerStaticDocTest {
private WebApplicationContext wac;
private MockMvc mockMvc;
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
/**
* 生成AsciiDocs格式文档
* @throws Exception
*/
public void generateAsciiDocs() throws Exception {
// 输出Ascii格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/asciidoc/generated"));
}
/**
* 生成Markdown格式文档
* @throws Exception
*/
public void generateMarkdownDocs() throws Exception {
// 输出Markdown格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.MARKDOWN)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/markdown/generated"));
}
/**
* 生成Confluence格式文档
* @throws Exception
*/
public void generateConfluenceDocs() throws Exception {
// 输出Confluence使用的格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/confluence/generated"));
}
/**
* 生成AsciiDocs格式文档,并汇总成一个文件
* @throws Exception
*/
public void generateAsciiDocsToFile() throws Exception {
// 输出Ascii到单文件
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/asciidoc/generated/all"));
}
/**
* 生成Markdown格式文档,并汇总成一个文件
* @throws Exception
*/
public void generateMarkdownDocsToFile() throws Exception {
// 输出Markdown到单文件
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.MARKDOWN)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/markdown/generated/all"));
}
/**
* 导出json
* @throws Exception
*/
public void createSwaggerJson() throws Exception {
String outputDir = "./docs";
MvcResult mvcResult = this.mockMvc.preform(get("/v2/api-docs")
.accept(MediaType.APPLCATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) {
writer.write(swaggerJson);
}
}
}
以上代码内容很简单,大致说明几个关键内容:
MarkupLanguage.ASCIIDOC:指定了要输出的最终格式。除了ASCIIDOC之外,还有MARKDOWN和CONFLUENCE_MARKUP
toFolder(Paths.get(“src/docs/asciidoc/generated”):指定最终生成文件的具体目录位置
输出到单个文件
如果不想分割结果文件,也可以通过替换toFolder(Paths.get(“src/docs/asciidoc/generated”)为toFile(Paths.get(“src/docs/asciidoc/generated/all”)),将转换结果输出到一个单一的文件中,这样可以最终生成html的也是单一的。
末尾
这里只提供了java代码生成文档,还可以通过maven来生成,没试过,有空试试,好像可以直接生成html和pdf,这点很诱人。
补充html生成
html是根据生成的.adoc文件生成的,通过maven插件。
pom.xml 添加以下内容,放在plugins标签内1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctro-maven-plugin</artifactId>
<version>1.5.3</version>
<configuration>
<sourceDirectory>docs/asciidoc/gengerated</sourceDir
ectory>
<outputDirectory>docs/asciidoc/html</outputDirectory>
<backend>html</backend>
<sourceHighlighter>coderay</sourceHighLighter>
<attributes>
<toc>left</toc>
<sectnums>true</sectnums>
</attributes>
</configuration>
</plugin>
执行插件就可以生成html到指定的文件夹,idea可以点开maven工具执行