1、Swagger简介
使用Swagger,就是把相关的信息存储在它定义的描述文件里面(yml或json格式),再通过维护这个描述文件可以去更新接口文档,以及生成各端代码
简而言之:代码即接口文档,接口文档即代码
2、参考网址
- 本文代码地址:https://gitee.com/enzoism/SpringBoot-MyBatis
(分支:spring_swagger_1) - Swagger整合参考网址:https://www.cnblogs.com/i-tao/p/10548181.html
- 更多controller参数配置:https://www.cnblogs.com/jtlgb/p/8532433.html
- 文档导出:https://www.cnblogs.com/yanqin/p/9145941.html
- 文档导出:https://www.jianshu.com/p/3441289c7afc
3、项目整合
3.1 Maven配置
先吐槽:不知道在哪搞了个maven镜像,下载的版本一致都不对,没有Swagger相关的标注,折腾了好久
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:/Users/zhifeng/.m2/repository/</localRepository>
<pluginGroups>
</pluginGroups>
<proxies>
</proxies>
<servers>
</servers>
<mirrors>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<profiles>
<profile>
<id>nexus</id>
<repositories>
<repository>
<id>central</id>
<url>http://maven.aliyun.com/nexus/content/repositories/central</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>ansj-repo</id>
<name>ansj Repository</name>
<url>http://maven.nlpcn.org/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
3.2 Swagger2.0整合
先导入pom依赖,然后配置SwaggerConfig,最后在Controller上添加标注,最后访问网址:http://localhost:9090/swagger-ui.html
- 先导入pom依赖
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
- 配置SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
ticketPar.name("Authorization").description("token")
.modelRef(new ModelRef("string")).parameterType("header")
.required(true).build(); //header中的ticket参数非必填,传空也可以
pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置什么参数
return new Docket(DocumentationType.SWAGGER_2)//文档类型:DocumentationType.SWAGGER_2
.apiInfo(apiInfo())//api信息
.select()//构建api选择器
.apis(RequestHandlerSelectors.basePackage("com.enzoism.controller"))//配置为Controller层的路径
.paths(PathSelectors.any())//api选择器选择包路径下任何api显示在文档中,根据需要配置所有还是用正则过滤
.build();//创建文档
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("标题")
.description("描述")
.termsOfServiceUrl("地址")
.version("1.0")
.build();
}
}
- controller添加标注
@GetMapping("user/{id}")
@ApiOperation(value="getUserMessage", notes="根据ID获取用户信息!")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
public User getUserById(@PathVariable String id){
User user = userService.getUserById(id);
return user;
}
4 多环境配置
以上的接口暴露会产生一个问题,如果在生产环境怎么屏蔽该地址?
- 4.1使用标识进行开关控制
- 4.2 针对不同的环境使用不同的application.propertites配置如下
### Swagger开发
swagger2.enable=false
- 4.3 访问失败
5、文档导出
接口的意义是文档,如果不能进行文档导出,貌似意义不是很大,只能是接口调用而已
- 5.1 新建工程,添加依赖
<!-- swagger-文档导出 -->
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>ch.netzwerg</groupId>
<artifactId>paleo-core</artifactId>
<version>0.10.2</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.9.2</version>
</dependency>
- 创建一个测试类
package com.enzoism;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
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.Paths;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SpringbootApplicationTests {
/**
* 生成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:9090/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:9090/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/markdown/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:9090/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:9090/v2/api-docs"))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/markdown/generated/all"));
}
/**
* 生成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:9090/v2/api-docs"))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/confluence/generated"));
}
}
- 5.3 直接运行测试接口
如果生成PDF并解决乱码,可以参考:https://www.jianshu.com/p/3441289c7afc