Swagger2与Springdoc集成与使用指南

以下是将 Swagger2 迁移到 Springdoc(支持 OpenAPI 3)的集成与使用指南,涵盖关键步骤、配置示例及注意事项:


1. 依赖配置

Springdoc 是支持 OpenAPI 3 规范的现代工具,适用于 Spring Boot 项目。需替换或添加以下依赖:


<dependency>
    <groupId>org.springdocgroupId>
    <artifactId>springdoc-openapi-starter-webmvc-uiartifactId>
    <version>2.2.0version> 
dependency>

注意:若项目原使用 springfox-swagger2,需移除相关依赖以避免冲突。


2. 基础配置

2.1 启用 Springdoc

Springdoc 自动配置,无需显式启用注解。在 application.propertiesapplication.yml 中配置基本信息:

# application.properties
springdoc.swagger-ui.enabled=true
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.version=1.0.0
springdoc.default-produces-media-type=application/json
2.2 自定义 OpenAPI 信息

通过 Java 配置类定义 API 元数据:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("API 文档")
                        .version("1.0")
                        .description("基于 Springdoc 的 OpenAPI 文档")
                        .contact(new Contact().name("开发者").email("[email protected]"))
                        .license(new License().name("Apache 2.0")));
    }
}

3. 注解使用

Springdoc 使用 io.swagger.v3.oas.annotations 注解替代 io.swagger.annotations。常用注解对照表:

Swagger2 注解 Springdoc 注解 用途
@Api @Tag 控制器分类描述
@ApiOperation @Operation 接口方法描述
@ApiParam @Parameter 方法参数描述
@ApiModel @Schema 数据模型描述
@ApiModelProperty @Schema 模型字段描述
@ApiResponse @ApiResponse 接口响应描述
示例代码
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@Tag(name = "用户管理", description = "用户相关操作接口")
@RequestMapping("/users")
public class UserController {

    @Operation(summary = "获取用户详情", description = "根据用户ID查询详细信息")
    @GetMapping("/{id}")
    public User getUser(
        @Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        // 业务逻辑
    }
}

4. 访问 Swagger UI

启动应用后,通过以下 URL 访问交互式文档界面:

  • Swagger UI: http://localhost:8080/swagger-ui.html
  • OpenAPI JSON: http://localhost:8080/v3/api-docs

5. 高级配置

5.1 分组多套 API

为不同模块配置多组 API 文档:

@Bean
public GroupedOpenApi publicApi() {
    return GroupedOpenApi.builder()
            .group("public-apis")
            .pathsToMatch("/api/public/**")
            .build();
}

@Bean
public GroupedOpenApi adminApi() {
    return GroupedOpenApi.builder()
            .group("admin-apis")
            .pathsToMatch("/api/admin/**")
            .build();
}
5.2 安全配置

集成 JWT 或 OAuth2 时,添加安全方案:

@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
            .components(new Components()
                    .addSecuritySchemes("bearerAuth", 
                        new SecurityScheme()
                            .type(SecurityScheme.Type.HTTP)
                            .scheme("bearer")
                            .bearerFormat("JWT")))
            .info(/* 略 */);
}

6. 与 Spring Security 集成

确保 Spring Security 允许访问文档端点:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                .anyRequest().authenticated()
            );
        return http.build();
    }
}

7. 迁移注意事项

  1. 移除旧依赖:彻底清除 springfox-swagger2swagger-annotations
  2. 注解替换:全局替换包路径 io.swagger.annotationsio.swagger.v3.oas.annotations
  3. 路径变化:Swagger UI 的默认路径从 /swagger-ui/ 变为 /swagger-ui.html

8. 常见问题

Q1: 文档页面无法加载?
  • 检查依赖冲突:确保无 springfox 残留依赖。
  • 验证路径配置:确认 springdoc.swagger-ui.path 未被覆盖。
Q2: 注解未生效?
  • 包路径正确性:确认使用 io.swagger.v3.oas.annotations 下的注解。
  • 方法签名匹配@Parameter 需直接修饰参数或配合 @RequestParam 使用。

通过以上步骤,可快速将项目从 Swagger2 迁移至 Springdoc,并充分利用 OpenAPI 3 的新特性。

你可能感兴趣的:(微服务,Swagger2,spring,boot,java,开发语言)