1迹卢、Swagger簡介
使用Swagger,就是把相關(guān)的信息存儲在它定義的描述文件里面(yml或json格式),再通過維護這個描述文件可以去更新接口文檔搓逾,以及生成各端代碼
簡而言之:代碼即接口文檔轮听,接口文檔即代碼
2骗露、參考網(wǎng)址
- 本文代碼地址:https://gitee.com/enzoism/SpringBoot-MyBatis
(分支:spring_swagger_1) - Swagger整合參考網(wǎng)址:https://www.cnblogs.com/i-tao/p/10548181.html
- 更多controller參數(shù)配置:https://www.cnblogs.com/jtlgb/p/8532433.html
- 文檔導出:https://www.cnblogs.com/yanqin/p/9145941.html
- 文檔導出:http://www.reibang.com/p/3441289c7afc
3、項目整合
3.1 Maven配置
先吐槽:不知道在哪搞了個maven鏡像血巍,下載的版本一致都不對萧锉,沒有Swagger相關(guān)的標注,折騰了好久
<?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上添加標注,最后訪問網(wǎng)址: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參數(shù)非必填鲫凶,傳空也可以
pars.add(ticketPar.build()); //根據(jù)每個方法名也知道當前方法在設置什么參數(shù)
return new Docket(DocumentationType.SWAGGER_2)//文檔類型:DocumentationType.SWAGGER_2
.apiInfo(apiInfo())//api信息
.select()//構(gòu)建api選擇器
.apis(RequestHandlerSelectors.basePackage("com.enzoism.controller"))//配置為Controller層的路徑
.paths(PathSelectors.any())//api選擇器選擇包路徑下任何api顯示在文檔中禀崖,根據(jù)需要配置所有還是用正則過濾
.build();//創(chuàng)建文檔
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("標題")
.description("描述")
.termsOfServiceUrl("地址")
.version("1.0")
.build();
}
}
- controller添加標注
@GetMapping("user/{id}")
@ApiOperation(value="getUserMessage", notes="根據(jù)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;
}
- 訪問網(wǎng)址:http://localhost:9090/swagger-ui.html
4 多環(huán)境配置
以上的接口暴露會產(chǎn)生一個問題,如果在生產(chǎn)環(huán)境怎么屏蔽該地址掀序?
- 4.1使用標識進行開關(guān)控制
- 4.2 針對不同的環(huán)境使用不同的application.propertites配置如下
### Swagger開發(fā)
swagger2.enable=false
- 4.3 訪問失敗
5帆焕、文檔導出
接口的意義是文檔,如果不能進行文檔導出,貌似意義不是很大叶雹,只能是接口調(diào)用而已
- 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>
- 創(chuàng)建一個測試類
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并解決亂碼,可以參考:http://www.reibang.com/p/3441289c7afc