Swagger API 操作排序

2022-01-22 00:00:00 swagger java spring-boot springfox

如何按字母顺序对我的操作进行排序,例如DELETE、GET、POST、PUT.

How do I sort my operation by method alphabetically e.g. DELETE, GET, POST, PUT.

我已阅读这篇文章,但它是 HTML 格式的,但就我而言,我已将 Swagger 集成到 Spring Boot 中,因此我需要在创建 Docket 时对其进行排序.

I have read from this post but it is in HTML but in my case, I have integrated Swagger into Spring Boot so I need to sort it when creating a Docket.

在 Swagger UI 中排序 API 方法

然后我在 Docket 中注意到了这个方法 operationOrdering(),但我仍然无法使其工作.

Then I noticed this method operationOrdering() in Docket, but I still cannot make it work.

推荐答案

我使用的是 Springfox 2.8.0 版,以下代码片段适用于我记录的 API:

I am using Springfox version 2.8.0 and following code snippet works for my documented API:

@Bean
UiConfiguration uiConfig() {
    return UiConfigurationBuilder
            .builder()
            .operationsSorter(OperationsSorter.METHOD)

            ...

            .build();
}

有 2 个可能的值:

  • OperationsSorter.ALPHA - 按路径
  • 的字母顺序对 API 端点进行排序
  • OperationsSorter.METHOD - 按method
  • 的字母顺序对 API 端点进行排序
  • OperationsSorter.ALPHA - sorts API endpoints alphabetically by path
  • OperationsSorter.METHOD - sorts API endpoints alphabetically by method

OperationsSorter.METHOD 就是您要查找的内容.

OperationsSorter.METHOD is what you are looking for.

替代使用operationOrdering():

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()

        ...

        .operationOrdering(new Ordering<Operation>() {
            @Override
            public int compare(Operation left, Operation right) {
                return left.getMethod().name().compareTo(right.getMethod().name());
            }
        })
}

但是,这不起作用,因为 Springfox 中的一个错误似乎仍然处于活动状态(Operation订购无效).

However, this does not work because of a bug in Springfox which seems to be still active (Operation ordering is not working).

相关文章