Swagger2与Springdoc集成与使用详解

Swagger2与Springdoc集成与使用详解

一、技术选型对比
  1. Swagger2(基于Springfox):

    • 支持OpenAPI 2.0规范
    • 注解体系:@Api/@ApiOperation
    • 配置类:Docket
    • 访问路径:/swagger-ui.html
  2. Springdoc

    • 支持OpenAPI 3.0规范
    • 注解体系:@Tag/@Operation
    • 自动配置机制
    • 访问路径:/swagger-ui/index.html
二、集成步骤
  1. 添加依赖(替换Springfox):
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.1.0</version>
</dependency>
  1. 基础配置类
@Configuration
@OpenAPIDefinition(
    info = @Info(
        title = "API文档",
        version = "1.0",
        description = "系统接口文档"
    )
)
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .components(new Components())
            .addSecurityItem(new SecurityRequirement().addList("JWT"));
    }
}
  1. 接口标注示例
@Tag(name = "用户模块")
@RestController
@RequestMapping("/users")
public class UserController {

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    public User getUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        return userService.getById(id);
    }
}
三、配置调优
# 开启文档生成(生产环境建议关闭)
springdoc.api-docs.enabled=true
# 分组配置示例
springdoc.group-configs[0].group=admin
springdoc.group-configs[0].paths-to-match=/admin/**
四、安全集成方案
@Configuration
@SecurityScheme(
    name = "JWT",
    type = SecuritySchemeType.HTTP,
    scheme = "bearer",
    bearerFormat = "JWT"
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 安全配置...
}
五、常见问题排查
  1. 依赖冲突

    • 移除springfox-swagger2springfox-swagger-ui
    • 检查是否包含springdoc-openapi-webflux-core(WebFlux项目专用)
  2. 接口未扫描

# 指定扫描包路径
springdoc.packagesToScan=com.example.controller
  1. 路径匹配问题(Spring Boot 2.6+):
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setPatternParser(PathPatternParser.defaultInstance);
    }
}
六、高级功能扩展
  1. 自定义响应模型
@Schema(description = "标准响应结构")
public class Result<T> {
    @Schema(description = "状态码")
    private Integer code;
    
    @Schema(description = "业务数据")
    private T data;
}
  1. 多版本文档管理
springdoc.version=1.2.0
springdoc.paths-to-match=/v2/**
  1. 性能优化建议
# 关闭未使用的处理器
springdoc.model-converters.enabled=false
springdoc.override-with-generic-response=false

最佳实践提示:建议在application-dev.yml中开启文档功能,在application-prod.yml中通过springdoc.api-docs.enabled=false关闭文档生成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酷爱码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值