簡(jiǎn)單介紹下Swagger2吧
算了不說(shuō)了。就是個(gè)文檔框架,具體的網(wǎng)上一大堆介紹
如何使用
- 導(dǎo)包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
- 加載配置類
package com.eliteai.smartiot.config.swagger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger能成為最受歡迎的REST APIs文檔生成工具之一,有以下幾個(gè)原因:
* Swagger 可以生成一個(gè)具有互動(dòng)性的API控制臺(tái),開(kāi)發(fā)者可以用來(lái)快速學(xué)習(xí)和嘗試API。
* Swagger 可以生成客戶端SDK代碼用于各種不同的平臺(tái)上的實(shí)現(xiàn)。
* Swagger 文件可以在許多不同的平臺(tái)上從代碼注釋中自動(dòng)生成。
* Swagger 有一個(gè)強(qiáng)大的社區(qū),里面有許多強(qiáng)悍的貢獻(xiàn)者
*
* @author MR.ZHANG
* @create 2018-09-18 10:06
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private static final String VERSION = "1.0.0";
@Value("${swagger.enable}")
private boolean enableSwagger;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(enableSwagger)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.eliteai.smartiot.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXXX軟件接口")
.description("Restful 風(fēng)格接口")
//服務(wù)條款網(wǎng)址
//.termsOfServiceUrl("http://xxxx")
.version(VERSION)
//.contact(new Contact("wesker", "url", "email"))
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
}
basePackage是指定掃描的包,這里要根據(jù)實(shí)際作修改
package com.eliteai.smartiot.config.swagger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置Swagger的資源映射路徑
*原有WebMvcConfigurerAdapter已經(jīng)過(guò)時(shí) 使用WebMvcConfigurer取代
* @author MR.ZHANG
* @create 2018-09-18 10:41
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${swagger.enable}")
private boolean enableSwagger;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (enableSwagger) {
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}
解釋下enableSwagger是多環(huán)境配置開(kāi)關(guān),一般生產(chǎn)環(huán)境中不想打開(kāi)swagger的uil界面,就可以讓其為false,當(dāng)然這個(gè)得在yml里增加支持
#----------------swagger配置-----------------------
swagger:
enable: false
- 在Controller里使用,這里直接貼代碼
/**
* 中央監(jiān)控中心Controller
*
* @author MR.ZHANG
* @create 2018-09-10 14:22
*/
@Api(value="/central", tags="中央監(jiān)控中心模塊")
@Controller
public class CentralMonitorController extends BaseController {
@ApiOperation(value="登陸頁(yè)面", notes = "中央監(jiān)控中心登陸界面")
@GetMapping("/")
public String adminPage() {
return "login";
}
@ApiOperation(value="管理員登陸", notes = "中央監(jiān)控中心管理員登陸", produces = "application/json", response = BaseResult.class)
@ApiResponses({@ApiResponse(code = CommonData.SUCCESS, message = "成功"),
@ApiResponse(code = CommonData.ERR_USER_NO_LOGIN, message = "限制登陸"),
@ApiResponse(code = CommonData.ERR_APP_INVALID_PWD, message = "賬號(hào)或密碼錯(cuò)誤")
})
@ApiImplicitParams({@ApiImplicitParam(name = "admin", value = "t_user name", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "pwd", value = "t_user password", required = true, dataType = "String", paramType = "query")})
@PostMapping("/login")
@ResponseBody
public BaseResult login(String admin, String pwd) {
}
- 運(yùn)行項(xiàng)目,瀏覽器輸入
http://localhost:8080/swagger-ui.html看看吧
靜態(tài)部署
有時(shí)候我們想要把文檔導(dǎo)出來(lái)給客戶或者其他人用,這時(shí)候總不能讓他們?nèi)サ顷戇@個(gè)地址吧。最好就是像以前我們手寫(xiě)文檔那樣給他們一個(gè)doc或者pdf。所以靜態(tài)部署這個(gè)需求就出來(lái)了。
如何部署
1. 引入依賴
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.10.1</version>
<scope>test</scope>
</dependency>
swagger2markup是一個(gè)開(kāi)源的項(xiàng)目,就是用來(lái)實(shí)現(xiàn)靜態(tài)部署的。支持導(dǎo)出html,markdown,pdf格式文檔。詳細(xì)可去https://github.com/13001260824/swagger了解下
asciidoctorj-pdf是一個(gè)將adoc文件轉(zhuǎn)pdf的插件
2. 配置插件
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<swaggerInput>http://localhost:8080/v2/api-docs</swaggerInput>
<outputDir>src/docs/asciidoc/generated</outputDir>
<config>
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
</config>
</configuration>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<configuration>
<sourceDirectory>src/docs/asciidoc/generated</sourceDirectory>
<outputDirectory>src/docs/asciidoc/html</outputDirectory>
<backend>html</backend>
<sourceHighlighter>coderay</sourceHighlighter>
<attributes>
<toc>left</toc>
</attributes>
</configuration>
</plugin>
看到配置里有一些路徑,是的那就是aodc和html文件生成的路徑。給個(gè)圖看一下吧

3. 編寫(xiě)測(cè)試程序,用來(lái)生成adoc文件
package com.eliteai.smartiot;
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.asciidoctor.cli.AsciidoctorInvoker;
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;
/**
* @author MR.ZHANG
* @create 2018-09-18 16:13
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {
@Test
public void generateAsciiDocs() throws Exception {
// 輸出Ascii格式
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withGeneratedExamples()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.build();
Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs"))
.withConfig(config)
.build()
.toFile(Paths.get("src/docs/asciidoc/generated/api"));
}
@Test
public void generatePDF() {
//樣式
String style = "pdf-style=E:\\themes\\theme.yml";
//字體
String fontsdir = "pdf-fontsdir=E:\\fonts";
//需要指定adoc文件位置
String adocPath = "E:\\all.adoc";
AsciidoctorInvoker.main(new String[]{"-a",style,"-a",fontsdir,"-b","pdf",adocPath});
}
}
generateAsciiDocs這個(gè)測(cè)試方法執(zhí)行后會(huì)在src/docs/asciidoc/generated目錄下生成api.adoc文件
4. 生成HTML文檔
asciidoctor:process-asciidoc

創(chuàng)建好后運(yùn)行

無(wú)意外的話會(huì)在src/docs/asciidoc/html下生成api.html
5. 生成PDF文檔并解決中文亂碼問(wèn)題
5.1 還記得https://github.com/13001260824/swagger這個(gè)地址嗎,進(jìn)去把這個(gè)項(xiàng)目download下來(lái),把目錄下的data目錄拷貝到E盤(pán)根目錄下(當(dāng)然哪都行啦)
5.2 去下載一個(gè)中文字體,后綴是.ttf結(jié)尾的,放到data/fonts目錄里
5.3 復(fù)制data/themes/default-theme.yml為theme.yml,打開(kāi)theme.yml并搜索mplus1p開(kāi)頭的文件名,換成5.2下載的中文字體
5.4 運(yùn)行測(cè)試程序中的generatePDF生成pdf文件。至此結(jié)束!
謝謝觀賞!
參考:
使用Swagger2Markup實(shí)現(xiàn)API文檔的靜態(tài)部署(一)
asciidoctor-pdf中文亂碼問(wèn)題或顯示不全