Skip to content

SpringBoot 整合 Swagger UI 3.0 生成接口文档

Swagger 是一个非常流行的工具,可以帮助我们自动生成 RESTful API 的文档。本文将详细介绍如何在 SpringBoot 项目中整合 Swagger UI 3.0,生成美观且功能强大的 API 文档。

添加 maven 依赖

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

配置 swagger

java
@Component
@Data
@EnableOpenApi
public class SwaggerConfig {

    @Bean
    public Docket userApiDoc() {
        return new Docket(DocumentationType.OAS_30)
                .pathMapping("/")
                .enable(true) // 是否开启swagger
                .apiInfo(apiInfo()) // 配置api信息
                .select() // 选择哪些接口发布
                .apis(RequestHandlerSelectors.basePackage("com.ssn.hub.api"))
                .paths(PathSelectors.ant("/api/**")) // 匹配路径
                .build()
                .securitySchemes(List.of(apiKey())) // 添加请求头
                .securityContexts(List.of(securityContext())); // 携带token
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("管理系统")
                .description("接口文档")
                .contact(new Contact("","",""))
                .version("V1.0.0")
                .build();
    }

    private ApiKey apiKey() {
        return new ApiKey("access-token", "access-token", "header");
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "global");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return List.of(new SecurityReference("access-token", authorizationScopes));
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();
    }

}

常见问题

  1. 要是系统集成了认证拦截器, 需要降 swagger ui 相关 url 排除, 如下:
java
@Configuration
public class SecurityConfig implements WebMvcConfigurer {

    private final AuthInterceptor authInterceptor;

    public SecurityConfig(AuthInterceptor authInterceptor) {
        this.authInterceptor = authInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor).excludePathPatterns("/api/login/**","/swagger-ui/**","/swagger-resources/**","/error/**","/favicon.ico","/v3/api-docs/**");
    }
}
  1. application.yml 需要修改路径匹配规则
yml
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

记住修改路径匹配的策略,不然会出现如下错误:

text
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null

总结

通过以上步骤,你可以在 SpringBoot 项目中轻松地整合 Swagger UI 3.0,生成美观且功能强大的 API 文档。这不仅提高了开发效率,也方便了前后端的协作

Released under the MIT License.