我使用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页面,则可以使用以下表单:
我遇到的问题是使用content-type application / json检测pageable参数,我不知道如何传递值来更改页面大小 . 似乎忽略了所有值 .
是否可以将查询参数作为JSON对象传递?或者是否可以配置Swagger为Pageable接口包含的getter生成独立的查询参数字段?
请注意我使用带有Gradle的Springfox:
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'
6 回答
这是Spring-Fox的一个已知问题 . 见问题#755 . 根据zdila的评论2,此时替代方法是添加@ApiImplicitParams,这不是理想的但它确实有效 .
![Swagger UI showing @ApiImplicitParams for Pageable]
1 https://github.com/springfox/springfox/issues/755
2 https://github.com/springfox/springfox/issues/755#issuecomment-135059871
基于Vineet Bhatia的答案,您可以将解决方案包装在自定义注释中以获得可重用性:
然后可以这样使用:
Vineet Bhatia对
@ApiImplicitParams
的回答看起来不错 . 但是我遇到了情况,当@ApiIgnor
和@ApiParam(hidden = true)
不起作用时你仍然可以观察到整体和可分页的参数 . 我通过添加下一行来解决这个问题我的
SwaggerConfig
中的Docket bean .当您没有在localhost上运行时,Vineet Bhatia的答案会有验证问题 . 它将争论整数参数,它们不对应于json模式 .
所以我将整数更改为字符串:
对于想要在2019年解决此问题的人 . 此配置通过springfox documentation工作正常,但您无法设置参数说明 .
代码就在这里 .
https://github.com/springfox/springfox/blob/ef1721afc4c910675d9032bee59aea8e75e06d27/springfox-data-rest/src/main/java/springfox/documentation/spring/data/rest/configuration/SpringDataRestConfiguration.java
尽管具有隐式参数的解决方案有效,但它引入了许多额外的脆弱代码 . 最后,我们采用了以下解决方案:
我们将
PageRequest
(实现Pageable
)传递给我们的服务,该服务返回Page
. (全部来自org.springframework.data.domain
) .org.springframework.data.web.PagedResourcesAssembler
通过控制器方法自动注入,并允许将项映射到org.springframework.hateoas.PagedResources
我们不需要动态排序,所以我们省略了;由于springfox与org.springframework.data.domain.Sort的搭配不好,所以它对添加排序提出了一些挑战 .