说明:本文写作目的单纯是记录一次项目搭建,以便于以后查看。
开发工具:IDEA;操作系统:MacOS


前言

Swagger2 是为了方便生产中生成统一标准规范的API文档生成工具。既方便开发团队成员查看,也方便最后接口文档的生成。本文仅记录本人如何搭建,具体对于swagger的介绍网上有很多相关文章供学习参考。


一、引入依赖

我是spring cloud 的项目架构,在我common模块的pom文件中加入swagger的依赖,我其他的服务模块都会引入common模块,所以swagger的功能也会被其他服务模块给使用。
我使用的是3.0.0的版本,所以不需要引入springfox-swagger2和swagger2-ui,直接引入springfox-boot-starter即可

<!-- swager2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

二、修改配置文件

在服务模块的yaml文件中加入以下代码:

swagger:
  enabled: true
  title: 测试接口
  description: 描述测试接口
  version: 1.0.0
  contact:
    name: Ryan Ren
    url: 
    email: xxx@qq.com  
  package: com.program.test.myTest
  base-path: /**
  exclude-path: /error, /ops/**

spring: 
  mvc:
    pathmatch: # 重要!否则会报错
      matching-strategy: ant_path_matcher

三.Docket编写

swagger 3.0的版本可以省略很多东西:
移除springfox-swagger2的依赖冲突
移除@EnableSwagger2注解
Docket可省略,也可自行配置
代码如下(示例):

@Configuration
public class SwaggerConfig {

    @Value(value = "${swagger.enabled}")
    private boolean swaggerEnabled;

    @Value(value = "${swagger.title}")
    private String swaggerTitle;

    @Value(value = "${swagger.description}")
    private String swaggerDescription;

    @Value(value = "${swagger.version}")
    private String swaggerVersion;

    @Value(value = "${swagger.package}")
    private String swaggerPackage;

    @Value(value = "${swagger.contact.name}")
    private String swaggerContactName;

    @Value(value = "${swagger.contact.url}")
    private String swaggerContactUrl;

    @Value(value = "${swagger.contact.email}")
    private String swaggerContactEmail;

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(swaggerEnabled)
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerPackage))
                .paths(PathSelectors.any())
                .build();
    }

    //构建api文档的详细信息函数
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title(swaggerTitle)
                //创建人
                .contact(new Contact(swaggerContactName, swaggerContactUrl, swaggerContactEmail))
                //版本号
                .version(swaggerVersion)
                //描述
                .description(swaggerDescription)
                .build();
    }
}

同时访问网页也发生了变化
http://localhost:port/swagger-ui/index.html
在这里插入图片描述


遇到的问题

  1. Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException:

问题原因:
SpringBoot更新至2.6.0,引发了这个bug。

解决方法:
在配置文件里加一条spring.mvc.pathmatch.matching-strategy=ant_path_matcher可解决

参考文章:https://www.jianshu.com/p/322f20aef4e1

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐