一、首先实现Springboot整合Swagger2生成

我自己使用的是 springboot 2.1.0,默认8080端口

 

springboot依赖 :

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.1.0.RELEASE</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent>

 

swagger依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

Springboot加上swagger注解:

@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {

   public static void main(String[] args) {
      SpringApplication.run(SpringbootSwagger2Application.class, args);
   }

}

配置swagger:

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(apiInfo())
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                        .paths(PathSelectors.any())
                        .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                        .title("springboot利用swagger构建api文档")
                        .description("简单优雅的restfun风格")
                        .termsOfServiceUrl("http://blog.csdn.net/saytime")
                        .version("1.0")
                        .build();
    }

}

 

测试的 controller(只加了swagger简单注释):

@RestController
@RequestMapping("/")
public class UserController extends BaseController{

    @Autowired
    private UserManager userManager;

    @ApiOperation(value="获取用户详细信息", notes="根据id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @RequestMapping(value = "user/query-by-id", method = RequestMethod.GET)
    public Result<UserVo> queryUserById(@RequestParam Long id) {
        return success(userManager.queryUserById(id));
    }
}

 

显示的页面 http://localhost:8080/swagger-ui.html

二、接入swagger-ui-layer(具体可参考:https://github.com/caspar-chen/swagger-ui-layer

swagger-ui-layer 是一个基于swagger的前端UI实现,是为了替换了默认的swagger-ui,让生成的文档更加友好和美观

swagger-ui-layer 要依赖swagger的注解功能,因为swagger-ui-layer 仅仅只是一个前端UI界面的实现,解析的数据来源于 /v2/api-docs

 

1、引入swagger-ui-layer包

<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>

 

2、修改SwaggerConfig类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket ProductApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                        .genericModelSubstitutes(DeferredResult.class)
                        .useDefaultResponseMessages(false)
                        .forCodeGeneration(false)
                        .pathMapping("/")
                        .select()
                        .build()
                        .apiInfo(productApiInfo());
    }

    private ApiInfo productApiInfo() {
        ApiInfo apiInfo = new ApiInfo("XXX系统数据接口文档",
                        "文档描述。。。",
                        "1.0.0",
                        "API TERMS URL",
                        "联系人邮箱",
                        "license",
                        "license url");
        return apiInfo;
    }
}

 

3、访问http://localhost:8080/docs.html  界面展示 

 

三、接入swagger2markup生成漂亮的 html文档(具体可参考https://github.com/Swagger2Markup/swagger2markup

 

1、接入依赖swagger2markup并重新引入swagger其他依赖:

<dependency>
   <groupId>io.github.swagger2markup</groupId>
   <artifactId>swagger2markup</artifactId>
   <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>swagger-ui</artifactId>
    <version>${swagger-ui.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox-swagger2.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox-swagger2.version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.hk2</groupId>
    <artifactId>spring-bridge</artifactId>
    <version>${spring-bridge.version}</version>
</dependency>

以上的版本号 

<swagger-ui.version>2.2.10</swagger-ui.version>
<spring-bridge.version>2.5.0-b34</spring-bridge.version>
<swagger.version>1.5.21</swagger.version>
<springfox-swagger2.version>2.6.1</springfox-swagger2.version>

 

2、添加maven打包成html的方式

<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <version>1.5.6</version>
    <configuration>
        <sourceDirectory>./docs/asciidoc/generated</sourceDirectory>
        <outputDirectory>./src/main/resources/static/v1</outputDirectory>
        <headerFooter>true</headerFooter>
        <doctype>book</doctype>
        <backend>html</backend>
        <sourceHighlighter>coderay</sourceHighlighter>
        <attributes>
            <!--菜单栏在左边-->
            <toc>left</toc>
            <!--多标题排列-->
            <toclevels>3</toclevels>
            <!--自动打数字序号-->
            <sectnums>true</sectnums>
        </attributes>
    </configuration>
</plugin>

 

3、测试类 运行(首先必须要运行项目 在运行测试类 因为是通过项目的url  默认 v2/api-docs 解析json数据)

package com.example.demo;

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;

/**
 * 生成格式文档的类,测试必须先启动项目再运行测试类,生成HTML的 mvn指令:mvn asciidoctor:process-asciidoc
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringbootSwagger2Application.class})
public class SwaggerDemoApplicationTests {

    // 接口数据json访问路径
    private final String URL = "http://localhost:8080/v2/api-docs";

    /**
     * 生成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(URL)).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(URL)).withConfig(config).build()
                        .toFolder(Paths.get("./docs/markdown/generated"));
    }


    /**
     * 生成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(URL)).withConfig(config).build()
                        .toFolder(Paths.get("./docs/confluence/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(URL)).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(URL)).withConfig(config).build()
                        .toFile(Paths.get("./docs/markdown/generated/all"));
    }

    @Test
    public void generateDosc() throws Exception {
        generateAsciiDocs();
        generateMarkdownDocs();
        generateConfluenceDocs();
        generateAsciiDocsToFile();
        generateMarkdownDocsToFile();
    }

}

4、使用 maven命令打包(docs文件路径为当项目路径的docs,也就是解析json后的数据文档)

mvn asciidoctor:process-asciidoc  

 

5、访问 静态文件,生成all.html后(路径和文件名可自己修改) 再重启项目 再访问 http://localhost:8080/v1/all.html

 

总结:

可能存在的问题

1、swagger2markup使用时swagger包冲突

springboot版本自带的swagger与新增依赖冲突 可根据maven打包命令 查看日志 去除包比如

<dependency>
    <groupId>io.github.swagger2markup</groupId>
    <artifactId>swagger2markup</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
        </exclusion>
        <exclusion>
            <groupId>net.sf.jopt-simple</groupId>
            <artifactId>jopt-simple</artifactId>
        </exclusion>
        <exclusion>
            <groupId>io.javaslang</groupId>
            <artifactId>javaslang</artifactId>
        </exclusion>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2、错误路径不监控  不显示 basic-error-controller

在swaggerconfig中配置

@Bean 
public Docket api() { 
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).pathMapping(“/”).select() // 选择那些路径和api会生成document 
.apis(RequestHandlerSelectors.any())// 对所有api进行监控 
// 不显示错误的接口地址 
.paths(Predicates.not(PathSelectors.regex(“/error.*”)))// 错误路径不监控 
.paths(PathSelectors.regex(“/.*”))// 对根下所有路径进行监控 
.build(); 
}

3、默认 v2/api-docs可能访问springboot自带的controller,可通过配置修改 json数据url

#Swagger 相关配置
springfox:
 documentation:
  swagger:
   v2:
    path: /ucs/swagger.json

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐