Swagger+spring boot 转换为html,PDF文

2017-04-20  本文已影响3884人  索隆大大

前言

使用Swagger将Restlet APIs转换为html和PDF文档。

主要是使用Swagger2Markup。官网提供了两种方式:
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.

我所使用的环境:Spring Boot + Gradle。
所以我使用的Swagger 是 springfox,如果你是Restlet JAX-RS等,可以使用restlet-framework(这些都可以在swagger的开源集合中找到)。

由于我的项目使用的是Gradle构建的,所以我使用的是Swagger2Markup Gradle Plugin。

官网提供了一个完整的Demo,可以生成html和pdf:http://swagger2markup.github.io/swagger2markup/1.3.1/#_demo

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

转换为 html或PDF的步骤

  1. 通过编写junit测试类生成一个实时的swagger.json。
  2. 将swagger.json转换为AsciiDoc。
  3. 增加AsciiDoc相关文档,具体可以参考Swagger2Markup Gradle PluginSwagger2Markup Maven Plugin文档。
  4. 将生成的asciiDoc通过AsciiDoc plugin转换为HTML和PDF.
  5. 将生成的html和pdf拷贝到可执行的jar包中,并部署他就可以让外界访问了。
    (图片来源:http://www.cnblogs.com/softidea/p/6251249.html
    Paste_Image.png

按照上述步骤开始编辑自己的应用。

1.在build.gradle中添加相关依赖和插件

buildscript {
    repositories {
        mavenCentral()
        //*********以下为swagger转换 pdf需要************//
        jcenter()
        maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
        //*********以上为swagger转换 pdf需要************//
        mavenLocal()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
        //*********以下为swagger转换 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转换 pdf需要************//
    }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
//*********以下为swagger转换 pdf需要************//
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'io.github.swagger2markup'
apply plugin: 'io.spring.dependency-management'
//*********以上为swagger转换 pdf需要************//

version = '1.2.0'

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

repositories {
    mavenCentral()
    //*********以下为swagger转换 pdf需要************//
    jcenter()
    maven { url 'https://repo.spring.io/snapshot' }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
    //*********以上为swagger转换 pdf需要************//
    mavenLocal()
}


ext {
    //设置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转换 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转换 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中设置swagger.json和asciiDoc生成路径,且配置到SystemProperty中,方便代码中使用。

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

test {
    //设置一些systemProperty
    systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
    systemProperty 'io.springfox.staticdocs.snippetsOutputDir', snippetsOutputDir
    systemProperty 'io.springfox.staticdocs.asciiDocOutputDir',asciiDocOutputDir
}

3.编写测试类生成swagger.json

也可以直接生成asciiDoc,跳过生成swagger.json然后通过swagger.json生成asciiDoc这一步,具体代码请参考: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路径,已经在build.gradle中配置
        String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
        //本项目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 启动类,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()
                //配置扫描的基础包
                .apis(RequestHandlerSelectors.basePackage("com.ops.commons.web"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("Controller中入参最好使用SpringMVC注解:@RequestBody,@RequestParam,@PathVariable<br>"
                        + "返回使用@ResponseBody或者ResponseEntity,区别:ResponseEntity可以包含Header和HttpStatus")
                .version("1.0")
                .build();
    }
}

4.添加AsciiDoc相关文档

打开官方Demo。将src/doc/asciidoc下面的文件拷贝到自己项目中。

5.将swagger.json生成asciiDoc文件

当增加Swagger2Markup Gradle Plugin插件时,他会自动增加一个convertSwagger2markup任务,当然你可以覆盖他。
在build.gradle中覆写convertSwagger2markup task:

convertSwagger2markup {
    //执行该task时先运行test,主要是运行Swagger2MarkupTest,让其生成swagger.json
    dependsOn test
    //入参为swagger.json
    swaggerInput "${swaggerOutputDir}/swagger.json"
    outputDir asciiDocOutputDir
    config = [
            'swagger2markup.pathsGroupedBy' : 'TAGS',
            'swagger2markup.extensions.springRestDocs.snippetBaseUri': snippetsOutputDir.getAbsolutePath()]
}

6.将asciiDoc转换为html和PDF。

在build.gradle中添加

asciidoctor {
    //依赖上面的swagger.json转换为asciiDoc任务,方便直接运行该任务时,先运行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拷贝到项目中

因为生成的文件时放在build下面的,拷贝到项目中,当启动了项目后,用户可以直接通过浏览器查看

jar {
    dependsOn asciidoctor
    //将生成的html和PDF拷贝到项目中
    from ("${asciidoctor.outputDir}/html5") {
        into 'static/docs'
    }
    from ("${asciidoctor.outputDir}/pdf") {
        into 'static/docs'
    }
}

ok,完成。

现在你可以运行gradle clean asciidoctor命令,查看生成的文档了,html路径:build\asciidoc\html5;pdf路径:build\asciidoc\pdf。

完整build.gradle

buildscript {
    repositories {
        mavenCentral()
        //*********以下为swagger转换 pdf需要************//
        jcenter()
        maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
        //*********以上为swagger转换 pdf需要************//
        mavenLocal()
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE'
        //*********以下为swagger转换 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转换 pdf需要************//
    }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'spring-boot'
//*********以下为swagger转换 pdf需要************//
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'io.github.swagger2markup'
apply plugin: 'io.spring.dependency-management'
//*********以上为swagger转换 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转换 pdf需要************//
    jcenter()
    maven { url 'https://repo.spring.io/snapshot' }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
    //*********以上为swagger转换 pdf需要************//
    mavenLocal()
}


ext {
    //asciiDoc生成路径
    asciiDocOutputDir = file("${buildDir}/asciidoc/generated")
    //swagger.json生成路径
    swaggerOutputDir = file("${buildDir}/swagger")
    snippetsOutputDir = file("${buildDir}/asciidoc/snippets")
    //设置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转换 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转换 pdf需要************//
    testCompile 'org.springframework.boot:spring-boot-starter-test'
    testCompile 'junit:junit'
    testCompile 'com.fasterxml.jackson.module:jackson-module-jsonSchema:2.6.5'
}


test {
    //设置一些systemProperty
    systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
    systemProperty 'io.springfox.staticdocs.snippetsOutputDir', snippetsOutputDir
    systemProperty 'io.springfox.staticdocs.asciiDocOutputDir',asciiDocOutputDir
}

convertSwagger2markup {
    //执行该task时先运行test,主要是运行Swagger2MarkupTest,让其生成swagger.json
    dependsOn test
    swaggerInput "${swaggerOutputDir}/swagger.json"
    outputDir asciiDocOutputDir
    config = [
            'swagger2markup.pathsGroupedBy' : 'TAGS',
            'swagger2markup.extensions.springRestDocs.snippetBaseUri': snippetsOutputDir.getAbsolutePath()]
}

asciidoctor {
    //依赖上面的swagger.json转换为asciiDoc任务,方便直接运行该任务时,先运行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拷贝到项目中
    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

上一篇下一篇

猜你喜欢

热点阅读