springBoot 2.7.x整合 swagger2.9

发布时间 2023-07-18 23:08:03作者: php薯片

1.添加依赖

        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2.添加 swagger的 config

package com.wk.mango.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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author wangkun
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 配置Swagger2相关的bean
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    /**
     * 此处主要是API文档页面显示信息
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("xx平台")
                .description("xx平台")
                .build();
    }
}

3.重启访问地址

http://localhost:8001/swagger-ui.html#/

4.报错处理办法

报错:Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

第一种处理办法(配合前两步的配置)

配置文件中添加如下配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

重启后访问 http://localhost:8001/swagger-ui.html#/

第二种处理办法

Swagger配置类添加@EnableWebMvc注解,使用此注解需要同时修改 pom.xml使用 springboot-start的依赖,注释 swagger相关依赖,配置如下:

<!--        <dependency>-->
<!--            <groupId>io.springfox</groupId>-->
<!--            <artifactId>springfox-swagger2</artifactId>-->
<!--            <version>2.9.2</version>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>io.springfox</groupId>-->
<!--            <artifactId>springfox-swagger-ui</artifactId>-->
<!--            <version>2.9.2</version>-->
<!--        </dependency>-->

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

重启后访问 http://localhost:8001/swagger-ui/index.html