大腿的博客

springboot swagger生成文档

字数统计: 1.5k阅读时长: 7 min
2018/12/19 Share

工作上前后台分离,有时候接口定义没定好导致开发阶段要修改接口,前台要接口每次都来问,想要及时改好的接口文档。两边都挺麻烦的。我项目里面使用了swagger有页面的文档,能不能生成静态文件呢?结果还真的可以,美滋滋

前言

此处从springboot引用swagger到导出一次讲解,搭建过程可能会遇见很多问题,还请根据实际情况搜索。

参考

swagger官网

swagger2markup

引用pom.xml

这里需要注意一点,我现在提供的pom是可以的,如果直接使用最新的swagger包,在使用swagger上没问题,但是后面生成静态文档会有报错
错误信息如下

1
java.lang.NoSuchMethodError: io.swagger.models.Response.responseSchema(Lio/swagger/models/Model;)Lio/swagger/models/Response;

意思就是方法没有,解决方法参考这篇博客。基本上的意思就是jar包版本的问题,依赖的某些包没有维护了导致的

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
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>1.5.16</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.16</version>
</dependency>

编写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
@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
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
@Api(value = "测试接口", tags = { "测试接口" })
@RestController
@RequestMapping("/demo")
public class DemoController {
private DemoService demoService;
@Resource
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}

@ApiOperation(value = "测试接口", notes = "测试接口")
@GetMapping(value = "getTest/{id}")
public MyResult<Demo> getDome(@PathVariable("id") String id) {
return demoService.getDemo(id);
}
...
...
}

到这一步启动项目,没报错的话浏览器输入localhost:8080/swagger-ui.html就可以看到swagger 的页面文档,还可以进行接口测试。

生成静态文档

静态文档的生成,写测试用例就行,也不一定是测试用例,如果你愿意再写个main方法或者写在功能代码里的话。

SwaggerStaticDocTest.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
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
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SwaggerTestApplication.class, webEnvironment = RANDOM_PORT)
public class SwaggerStaticDocTest {
@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

/**
* 生成AsciiDocs格式文档
* @throws Exception
*/
@Test
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
*/
@Test
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
*/
@Test
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
*/
@Test
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
*/
@Test
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
*/
@Test
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

from(new URL(“http://localhost:8080/v2/api-docs"):指定了生成静态部署文档的源头配置,可以是这样的URL形式,也可以是符合Swagger规范的String类型或者从文件中读取的流。如果是对当前使用的Swagger项目,我们通过使用访问本地Swagger接口的方式,如果是从外部获取的Swagger文档配置文件,就可以通过字符串或读文件的方式

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工具执行

原文作者:大腿君的大腿君

原文链接:https://shiyuquan.github.io/2018/12/19/springboot-swagger生成文档/

发表日期:2018-12-19 15:06:45

更新日期:2018-12-20 13:38:07

版权声明:来自于大腿的许可

CATALOG
  1. 1. 前言
  2. 2. 引用pom.xml
  3. 3. 编写SwaggerConfig.java
  4. 4. controller接口例子
  5. 5. 生成静态文档
  6. 6. 末尾
  7. 7. 补充html生成