Spring Pageable 接口的 Swagger 文档

新手上路,请多包涵

我使用 Spring Boot 开发了一个微服务。 REST API 的文档是用 Swagger 制作的。一些 REST 资源利用 Spring 概念免费提供分页。下面是一个例子:

 @RequestMapping(value = "/buckets", method = GET)
public PagedResources list(Pageable pageable, PagedResourcesAssembler assembler) {
    return bucketService.listBuckets(pageable, assembler);
}

如果我打开 Swagger 页面,可以使用以下表格获取资源:

在此处输入图像描述

我遇到的问题是,使用内容类型 application/json 检测到可分页参数,我不知道如何传递一个值来更改页面大小,例如。所有的值似乎都被忽略了。

是否可以将查询参数作为 JSON 对象传递?或者是否可以配置 Swagger 为 Pageable 接口包含的 getter 生成独立的查询参数字段?

请注意,我将 Springfox 与 Gradle 一起使用:

 compile 'io.springfox:springfox-spring-web:2.3.1'
compile 'io.springfox:springfox-swagger2:2.3.1'
compile 'io.springfox:springfox-swagger-ui:2.3.1'

原文由 Laurent 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

这是 Spring-Fox 的一个已知问题。请参阅问题 #755 。根据 zdila 的评论 2 ,此时替代方法是添加 @ApiImplicitParams,这并不理想,但它确实有效。

 @ApiImplicitParams({
    @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query",
            value = "Results page you want to retrieve (0..N)"),
    @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query",
            value = "Number of records per page."),
    @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query",
            value = "Sorting criteria in the format: property(,asc|desc). " +
                    "Default sort order is ascending. " +
                    "Multiple sort criteria are supported.")
})

[ ![显示可分页的@ApiImplicitParams 的 Swagger UI]](https://i.stack.imgur.com/7v041.png)

1 https://github.com/springfox/springfox/issues/755

2 https://github.com/springfox/springfox/issues/755#issuecomment-135059871

原文由 Vineet Bhatia 发布,翻译遵循 CC BY-SA 3.0 许可协议

基于 Vineet Bhatia 的回答,您可以将解决方案包装在自定义注释中以实现可重用性:

 @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ApiImplicitParams({
    @ApiImplicitParam(name = "page", dataType = "int", paramType = "query", value = "Results page you want to retrieve (0..N)"),
    @ApiImplicitParam(name = "size", dataType = "int", paramType = "query", value = "Number of records per page."),
    @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", value = "Sorting criteria in the format: property(,asc|desc). "
            + "Default sort order is ascending. " + "Multiple sort criteria are supported.") })
@interface ApiPageable {
}

然后可以这样使用:

 @ApiPageable
public Page<Data> getData(Pageable pageRequest) {

原文由 Sean Connolly 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题