spring Boot 配置 swagger2 流程 及遇到问题记录

174 阅读1分钟

spring boot 配置 swagger2 流程

  1. 在pom.xml 文件配置依赖 这个pom.xml 就是配置依赖的地方
<!-- 引入 swagger2 依赖 -->
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.8.0</version>
</dependency>
<!-- swagger2 图形化依赖 -->
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.8.0</version>
</dependency>
  1. 然后在Java项目里面创建一个config文件夹用来写对应的配置文件
package com.example.demo.config;

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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * Swagger的配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径,控制器类包
                .apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 集成 Swagger2 测试接口文档")
                //创建人
                .contact(new Contact("李白", "http://www.beidu.com", "libai@350.com"))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}
  1. 这里有两个个需要注意的地方
  • spring boot 不会自动更新引入的依赖 可能是我没配置吧 这里手动更新一下就好了。
  • 主要是这个:引入的swagger2依赖和spring boot版本不一致 然后运行的时候报错如下:
  • Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
  • 造成这个主要原因是 当前的swagger2 版本 和 spring boot版本不匹配 修改下swagger版本就好了