ZBLOG

swagger 如何添加 路由前缀

在使用 Swagger 配置路由时,可以通过添加 @RequestMapping 注解来指定路由前缀。例如,假设我们要为一个名为 UserController 的控制器添加路由前缀 /api/v1/users,那么可以在控制器类上添加如下注解:

@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    // controller methods here...
}

这样,该控制器中定义的所有路由都会以 /api/v1/users 作为前缀,例如 GET /api/v1/users/{id}POST /api/v1/users 等路由。在 Swagger 中,可以直接在 Docket 配置对象的 pathMapping() 方法中指定路由前缀,如下所示:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.controllers"))
            .paths(PathSelectors.any())
            .build()
            .pathMapping("/api/v1/users"); // 设置路由前缀
    }
}

这里我们将路由前缀设置为 /api/v1/users,这样 Swagger 中显示的 API 路径也会加上该前缀。如果你希望在 Swagger 文档中去掉路由前缀,可以在 Docket 配置对象的 apiInfo() 方法中指定 basePath 属性为空字符串,如下所示:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.controllers"))
        .paths(PathSelectors.any())
        .build()
        .pathMapping("/api/v1/users")
        .apiInfo(apiInfo().basePath(""));
}

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=2523

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?