SpringBoot2.7.X整合Swagger3

这里使用的 SpringBoot 2.7.3 的版本,在创建项目完成后需要进行以下操作

添加POM

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

添加YML

# SpringBoot 2.6以后的版本,默认使用 PathPatternMatcher;Springfox使用的是 AntPathMatcher
# 不修改为 ant_path_matcher 会报出异常:
# org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

增加 Swagger3Config 配置类


import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
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;

/**
 * Swagger3 配置
 *
 * <p>http://localhost/swagger-ui/index.html
 */
@Configuration
public class Swagger3Config {
  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("什么系统的 接口文档")
        .description("接口文档描述")
        .contact(new Contact("作者名字", "作者主页", "作者邮箱"))
        .version("版本号")
        .build();
  }

  @Bean
  public Docket initDocket(Environment env) {
    // 设置要暴漏接口文档的配置环境
    // spring.profiles.active为 dev 或 test启用swagger
    Profiles profile = Profiles.of("dev", "test");
    boolean flag = env.acceptsProfiles(profile);
    return new Docket(DocumentationType.OAS_30)
        .apiInfo(apiInfo())
        .enable(flag)
        .groupName("分组名字")
        .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(Tag.class))
        .paths(PathSelectors.any())
        .build();
  }
}

访问地址

(注意主机和端口号设置):http://localhost/swagger-ui/index.html

使用

// 在Swagger的配置中
// 按Tag注解
.apis(RequestHandlerSelectors.withClassAnnotation(Tag.class))
// 匹配所有
.paths(PathSelectors.any())
    
// 对应Controller
@Tag(name = "index-controller", description = "主页测试")
@RestController
@RequestMapping("/")
public class IndexController {

  @Operation(summary = "主页", description = "测试")
  @GetMapping("/index")
  public String index() {
    return "成功";
  }
}

// 按包名
.apis(RequestHandlerSelectors.basePackage("com.ex.bianque"))

// 在配置文件中设置,按正则匹配路径
.paths(PathSelectors.regex("/user/.*"))
    

SpringBoot2.7.X整合Swagger3
https://元气码农少女酱.我爱你/317856722e5e/
作者
元气码农少女酱
发布于
2023年5月2日
许可协议