史上最簡(jiǎn)單的Swagger2實(shí)現(xiàn)API文檔的靜態(tài)部署并支持導(dǎo)出PDF并解決中文亂碼問(wèn)題

簡(jiǎn)單介紹下Swagger2吧
算了不說(shuō)了。就是個(gè)文檔框架,具體的網(wǎng)上一大堆介紹

如何使用

  1. 導(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>
  1. 加載配置類
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
  1. 在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) {
}
  1. 運(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è)圖看一下吧


image.png

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

image.png

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

無(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.ymltheme.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)題或顯示不全

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 如果生命都不復(fù)存在。 你將何去何從,你沒(méi)有了抱怨。 沒(méi)有了想要擁有的一切,如一絲青煙,不知飄往何處,會(huì)回頭看這一世...
    似塵沙閱讀 162評(píng)論 0 0
  • 如果喜歡也要努力的話,那就不是喜歡了,是因?yàn)榇糁粔K舒服,開(kāi)心,才喜歡,而不是我努力去喜歡你……
    煎蛋品閱讀 192評(píng)論 0 0
  • 說(shuō)實(shí)話,如果給你看上面的那張海報(bào),告訴你,這是一部電視劇的官方宣傳照。那么,你看到這張照片,會(huì)有興趣去看這部電視嗎...
    我是王慧閱讀 4,079評(píng)論 2 6
  • 最近規(guī)律的生活,讓我有一種感慨:在我的生命里,讓我感到安穩(wěn)的事情,大多不對(duì)人。比如福海的夕陽(yáng)、農(nóng)園的碗蒸青菜、宿舍...
    tirnanog閱讀 320評(píng)論 0 0

友情鏈接更多精彩內(nèi)容