Swagger+spring boot 轉(zhuǎn)換為html,PDF文件等

前言

使用Swagger將Restlet APIs轉(zhuǎn)換為html和PDF文檔。

主要是使用Swagger2Markup。官網(wǎng)提供了兩種方式:
You can use Swagger2Markup to convert your contract-first Swagger YAML file into a human-readable format and combine it with hand-written documentation.

  1. you can choose the code-first approach and use Swagger2Markup together with Swagger JAX-RS, springfox or spring-restdocs.

  2. If you are Gradle or Maven user, you can also use the Swagger2Markup Gradle Plugin or Swagger2markup Maven Plugin.

我所使用的環(huán)境:Spring Boot + Gradle。
所以我使用的Swagger 是 springfox,如果你是Restlet JAX-RS等,可以使用restlet-framework(這些都可以在swagger的開(kāi)源集合中找到)。

由于我的項(xiàng)目使用的是Gradle構(gòu)建的,所以我使用的是Swagger2Markup Gradle Plugin。

官網(wǎng)提供了一個(gè)完整的Demo,可以生成html和pdf:http://swagger2markup.github.io/swagger2markup/1.3.1/#_demo

官方Demo是使用Swagger2Markup Gradle Plugin插件生成的,當(dāng)然你也可以使用MAVEN插件,插件的使用例子如下:
Swagger2Markup Gradle Plugin:https://github.com/Swagger2Markup/swagger2markup-gradle-project-template
Swagger2Markup Maven Plugin:https://github.com/Swagger2Markup/swagger2markup-maven-project-template

轉(zhuǎn)換為 html或PDF的步驟

  1. 通過(guò)編寫(xiě)junit測(cè)試類生成一個(gè)實(shí)時(shí)的swagger.json。
  2. 將swagger.json轉(zhuǎn)換為AsciiDoc。
  3. 增加AsciiDoc相關(guān)文檔,具體可以參考Swagger2Markup Gradle PluginSwagger2Markup Maven Plugin文檔。
  4. 將生成的asciiDoc通過(guò)AsciiDoc plugin轉(zhuǎn)換為HTML和PDF.
  5. 將生成的html和pdf拷貝到可執(zhí)行的jar包中,并部署他就可以讓外界訪問(wèn)了。
    (圖片來(lái)源:http://www.cnblogs.com/softidea/p/6251249.html
    Paste_Image.png

按照上述步驟開(kāi)始編輯自己的應(yīng)用。

1.在build.gradle中添加相關(guān)依賴和插件

buildscript {
    repositories {
        mavenCentral()
        //*********以下為swagger轉(zhuǎn)換 pdf需要************//
        jcenter()
        maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
        //*********以上為swagger轉(zhuǎn)換 pdf需要************//
        mavenLocal()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
        //*********以下為swagger轉(zhuǎn)換 pdf需要************//
        //asciidoc 插件
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
        classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.10.1'
        //swagger2markup 插件
        classpath 'io.github.swagger2markup:swagger2markup-spring-restdocs-ext:1.2.0'
        classpath 'io.github.swagger2markup:swagger2markup-gradle-plugin:1.2.0'
        //*********以上為swagger轉(zhuǎn)換 pdf需要************//
    }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
//*********以下為swagger轉(zhuǎn)換 pdf需要************//
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'io.github.swagger2markup'
apply plugin: 'io.spring.dependency-management'
//*********以上為swagger轉(zhuǎn)換 pdf需要************//

version = '1.2.0'

tasks.withType(JavaCompile) {
    sourceCompatibility = "1.8"
    targetCompatibility = "1.8"
    options.deprecation = true
}

repositories {
    mavenCentral()
    //*********以下為swagger轉(zhuǎn)換 pdf需要************//
    jcenter()
    maven { url 'https://repo.spring.io/snapshot' }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
    //*********以上為swagger轉(zhuǎn)換 pdf需要************//
    mavenLocal()
}


ext {
    //設(shè)置springfox版本
    springfoxVersion = '2.5.0'
}

dependencies {
    //json
    compile "org.codehaus.jackson:jackson-mapper-asl:1.9.12"
    /*fastjson*/
    compile "com.alibaba:fastjson:1.1.39"
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-actuator'
    compile 'com.google.guava:guava:18.0'
    compile 'net.logstash.logback:logstash-logback-encoder:4.5.1'
    compile("com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.6.5")
    compile("com.fasterxml.jackson.module:jackson-module-afterburner:2.6.5")
    //*********以下為swagger轉(zhuǎn)換 pdf需要************//
    compile 'io.swagger:swagger-annotations:1.5.6'
    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.1'
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.1'
    testCompile "io.springfox:springfox-bean-validators:${springfoxVersion}"
    testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
    //*********以上為swagger轉(zhuǎn)換 pdf需要************//
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'junit:junit'
    testCompile 'com.fasterxml.jackson.module:jackson-module-jsonSchema:2.6.5'
}

2.在build.gradle中設(shè)置swagger.json和asciiDoc生成路徑,且配置到SystemProperty中,方便代碼中使用。

ext {
    //asciiDoc生成路徑
    asciiDocOutputDir = file("${buildDir}/asciidoc/generated")
    //swagger.json生成路徑
    swaggerOutputDir = file("${buildDir}/swagger")
    snippetsOutputDir = file("${buildDir}/asciidoc/snippets")
    //設(shè)置springfox版本
    springfoxVersion = '2.5.0'
}

test {
    //設(shè)置一些systemProperty
    systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
    systemProperty 'io.springfox.staticdocs.snippetsOutputDir', snippetsOutputDir
    systemProperty 'io.springfox.staticdocs.asciiDocOutputDir',asciiDocOutputDir
}

3.編寫(xiě)測(cè)試類生成swagger.json

也可以直接生成asciiDoc,跳過(guò)生成swagger.json然后通過(guò)swagger.json生成asciiDoc這一步,具體代碼請(qǐng)參考:http://swagger2markup.github.io/swagger2markup/1.3.1/#_spring_boot_and_springfox

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets")
@SpringBootTest(classes = {CommonToolsApplication.class, SwaggerAutoConfiguration.class})
@AutoConfigureMockMvc
public class Swagger2MarkupTest {

    private static final Logger LOG = LoggerFactory.getLogger(Swagger2MarkupTest.class);

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void createSpringfoxSwaggerJson() throws Exception {
        //String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath();
        //獲取生成swagger.json路徑,已經(jīng)在build.gradle中配置
        String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
        //本項(xiàng)目api路徑
        MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
                .accept(MediaType.APPLICATION_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);
        }
    }
}

其中CommonToolsApplication為spring boot 啟動(dòng)類,SwaggerAutoConfiguration為Swagger配置類

@SpringBootApplication
public class CommonToolsApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommonToolsApplication.class, args);
    }
}
@Configuration
@EnableSwagger2
public class SwaggerAutoConfiguration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //配置掃描的基礎(chǔ)包
                .apis(RequestHandlerSelectors.basePackage("com.ops.commons.web"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構(gòu)建RESTful APIs")
                .description("Controller中入?yún)⒆詈檬褂肧pringMVC注解:@RequestBody,@RequestParam,@PathVariable<br>"
                        + "返回使用@ResponseBody或者ResponseEntity,區(qū)別:ResponseEntity可以包含Header和HttpStatus")
                .version("1.0")
                .build();
    }
}

4.添加AsciiDoc相關(guān)文檔

打開(kāi)官方Demo。將src/doc/asciidoc下面的文件拷貝到自己項(xiàng)目中。

5.將swagger.json生成asciiDoc文件

當(dāng)增加Swagger2Markup Gradle Plugin插件時(shí),他會(huì)自動(dòng)增加一個(gè)convertSwagger2markup任務(wù),當(dāng)然你可以覆蓋他。
在build.gradle中覆寫(xiě)convertSwagger2markup task:

convertSwagger2markup {
    //執(zhí)行該task時(shí)先運(yùn)行test,主要是運(yùn)行Swagger2MarkupTest,讓其生成swagger.json
    dependsOn test
    //入?yún)閟wagger.json
    swaggerInput "${swaggerOutputDir}/swagger.json"
    outputDir asciiDocOutputDir
    config = [
            'swagger2markup.pathsGroupedBy' : 'TAGS',
            'swagger2markup.extensions.springRestDocs.snippetBaseUri': snippetsOutputDir.getAbsolutePath()]
}

6.將asciiDoc轉(zhuǎn)換為html和PDF。

在build.gradle中添加

asciidoctor {
    //依賴上面的swagger.json轉(zhuǎn)換為asciiDoc任務(wù),方便直接運(yùn)行該任務(wù)時(shí),先運(yùn)行convertSwagger2markup
    dependsOn convertSwagger2markup
    sources {
        include 'index.adoc'
    }
    backends = ['html5', 'pdf']
    attributes = [
            doctype: 'book',
            toc: 'left',
            toclevels: '3',
            numbered: '',
            sectlinks: '',
            sectanchors: '',
            hardbreaks: '',
            generated: asciiDocOutputDir
    ]
}

7.將生成的html和PDF拷貝到項(xiàng)目中

因?yàn)樯傻奈募r(shí)放在build下面的,拷貝到項(xiàng)目中,當(dāng)啟動(dòng)了項(xiàng)目后,用戶可以直接通過(guò)瀏覽器查看

jar {
    dependsOn asciidoctor
    //將生成的html和PDF拷貝到項(xiàng)目中
    from ("${asciidoctor.outputDir}/html5") {
        into 'static/docs'
    }
    from ("${asciidoctor.outputDir}/pdf") {
        into 'static/docs'
    }
}

ok,完成。

現(xiàn)在你可以運(yùn)行g(shù)radle clean asciidoctor命令,查看生成的文檔了,html路徑:build\asciidoc\html5;pdf路徑:build\asciidoc\pdf。

完整build.gradle

buildscript {
    repositories {
        mavenCentral()
        //*********以下為swagger轉(zhuǎn)換 pdf需要************//
        jcenter()
        maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
        //*********以上為swagger轉(zhuǎn)換 pdf需要************//
        mavenLocal()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
        //*********以下為swagger轉(zhuǎn)換 pdf需要************//
        //asciidoc 插件
        classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
        classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.10.1'
        //swagger2markup 插件
        classpath 'io.github.swagger2markup:swagger2markup-spring-restdocs-ext:1.2.0'
        classpath 'io.github.swagger2markup:swagger2markup-gradle-plugin:1.2.0'
        //*********以上為swagger轉(zhuǎn)換 pdf需要************//
    }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
//*********以下為swagger轉(zhuǎn)換 pdf需要************//
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'io.github.swagger2markup'
apply plugin: 'io.spring.dependency-management'
//*********以上為swagger轉(zhuǎn)換 pdf需要************//

version = '1.2.0'

tasks.withType(JavaCompile) {
    sourceCompatibility = "1.8"
    targetCompatibility = "1.8"
    options.deprecation = true
    options.encoding = 'UTF-8'
    options.compilerArgs << "-Xlint:unchecked"
}

repositories {
    mavenCentral()
    //*********以下為swagger轉(zhuǎn)換 pdf需要************//
    jcenter()
    maven { url 'https://repo.spring.io/snapshot' }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
    //*********以上為swagger轉(zhuǎn)換 pdf需要************//
    mavenLocal()
}


ext {
    //asciiDoc生成路徑
    asciiDocOutputDir = file("${buildDir}/asciidoc/generated")
    //swagger.json生成路徑
    swaggerOutputDir = file("${buildDir}/swagger")
    snippetsOutputDir = file("${buildDir}/asciidoc/snippets")
    //設(shè)置springfox版本
    springfoxVersion = '2.5.0'
}

dependencies {
    //servlet-api
    compile "javax.servlet:javax.servlet-api:3.1.0"
    //json
    compile "org.codehaus.jackson:jackson-mapper-asl:1.9.12"
    /*fastjson*/
    compile "com.alibaba:fastjson:1.1.39"
    compile 'org.springframework.boot:spring-boot-starter-web'
    compile 'org.springframework.boot:spring-boot-starter-actuator'
    compile 'com.google.guava:guava:18.0'
    compile 'net.logstash.logback:logstash-logback-encoder:4.5.1'
    compile("com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.6.5")
    compile("com.fasterxml.jackson.module:jackson-module-afterburner:2.6.5")
    //*********以下為swagger轉(zhuǎn)換 pdf需要************//
    compile 'io.swagger:swagger-annotations:1.5.6'
    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.1'
    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.1'
    testCompile "io.springfox:springfox-bean-validators:${springfoxVersion}"
    testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
    //*********以上為swagger轉(zhuǎn)換 pdf需要************//
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'junit:junit'
    testCompile 'com.fasterxml.jackson.module:jackson-module-jsonSchema:2.6.5'
}


test {
    //設(shè)置一些systemProperty
    systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
    systemProperty 'io.springfox.staticdocs.snippetsOutputDir', snippetsOutputDir
    systemProperty 'io.springfox.staticdocs.asciiDocOutputDir',asciiDocOutputDir
}

convertSwagger2markup {
    //執(zhí)行該task時(shí)先運(yùn)行test,主要是運(yùn)行Swagger2MarkupTest,讓其生成swagger.json
    dependsOn test
    swaggerInput "${swaggerOutputDir}/swagger.json"
    outputDir asciiDocOutputDir
    config = [
            'swagger2markup.pathsGroupedBy' : 'TAGS',
            'swagger2markup.extensions.springRestDocs.snippetBaseUri': snippetsOutputDir.getAbsolutePath()]
}

asciidoctor {
    //依賴上面的swagger.json轉(zhuǎn)換為asciiDoc任務(wù),方便直接運(yùn)行該任務(wù)時(shí),先運(yùn)行convertSwagger2markup
    dependsOn convertSwagger2markup
    sources {
        include 'index.adoc'
    }
    backends = ['html5', 'pdf']
    attributes = [
            doctype: 'book',
            toc: 'left',
            toclevels: '3',
            numbered: '',
            sectlinks: '',
            sectanchors: '',
            hardbreaks: '',
            generated: asciiDocOutputDir
    ]
}

jar {
    dependsOn asciidoctor
    //將生成的html和PDF拷貝到項(xiàng)目中
    from ("${asciidoctor.outputDir}/html5") {
        into 'static/docs'
    }
    from ("${asciidoctor.outputDir}/pdf") {
        into 'static/docs'
    }
}


參考文檔
官方文檔:http://swagger2markup.github.io/swagger2markup/1.3.1/
官方Demo:https://github.com/Swagger2Markup/spring-swagger2markup-demo
springfox官方文檔:http://springfox.github.io/springfox/docs/current/#usage-guide
http://www.cnblogs.com/softidea/p/6251249.html

最后編輯于
?著作權(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)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評(píng)論 6 342
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評(píng)論 19 139
  • 場(chǎng)景 有時(shí)候需要為前端開(kāi)發(fā)者提供Restful Api說(shuō)明文檔,通過(guò)word文檔創(chuàng)建和修改非常耗時(shí),希望有一種比較...
    飛天豌豆狼閱讀 9,935評(píng)論 4 6
  • 今天值班,閑來(lái)無(wú)事,在微信上聽(tīng)了李笑來(lái)的《賣(mài)知識(shí)的最正確姿勢(shì)》,知道了很多好的理念,知道了為什么時(shí)代發(fā)展到今天知識(shí)...
    春曉育兒講堂閱讀 591評(píng)論 0 0
  • 初入群來(lái),如誤入桃花源,復(fù)行數(shù)十步,豁然開(kāi)朗。感覺(jué)終于找到了組織,如迷途得返的羔羊,落入江海之雨滴,雄心頓起...
    OnTheRoad在路上閱讀 573評(píng)論 2 3

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