【问题标题】:endpoints group by resources swagger annotation?端点按资源招摇注释分组?
【发布时间】:2018-11-07 02:28:45
【问题描述】:

我正在使用 Spring 进行 REST API 开发。而且我有一些 API,其中有很多端点。当我打开 swagger ui 时,它看起来已经打包好了。

我刚刚阅读了this 文章,看到我们可以根据资源级别对端点进行分组。

我只是想知道如何通过 Spring 的 swagger 注释来实现这一点。如果有人可以举例说明,我将不胜感激。

而且我只是想知道我们是否可以重新组合(更高级别的分组)我们以上述方式推导出的组?

【问题讨论】:

    标签: spring rest api swagger springfox


    【解决方案1】:

    ********** 解决方案 1:(使用组) **********

    只需为每个组定义多个Docket bean,您将根据需要获得逻辑分组。

    @Bean
    public Docket api1() {
    
    return new Docket(DocumentationType.SWAGGER_2)
        .groupName("users")
        .select()
        .paths(PathSelectors.ant("/api/users/**"))
        .build();
    }
    
    @Bean
    public Docket api2() {
    
    return new Docket(DocumentationType.SWAGGER_2)
        .groupName("products")
        .select()
        .paths(PathSelectors.ant("/api/products/**"))
        .build();
    }
    

    现在您将在您的 swagger 用户界面中获得两个组,如下所示。

    ********** 解决方案 2:(使用标签) **********

    你不需要定义多个Docket bean,一个就够了。

    @Bean
    public Docket api1() {
    
    // here tags is optional, it just adds a description in the UI
    // by default description is class name, so if you use same tag using 
    // `@Api` on different classes it will pick one of the class name as 
    // description, so better define your own description for them
    return new Docket(DocumentationType.SWAGGER_2)
        .tags(new Tag("users", "users related"), 
              new Tag("products", "products related"))
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.github"))
        .build();
    }
    

    之后,您只需使用 @Api(在类级别,所有方法的默认值)或 @ApiOperation(在方法级别,将覆盖类级别的值)注释您的 api 方法。

    @RestController
    @RequestMapping("/api/products")
    @Api(tags = "products")
    public class ProductController {
    
        @ApiOperation(value = "", tags = "products")
        @RequestMapping(method = RequestMethod.POST)
        @ResponseStatus(HttpStatus.CREATED)
        public Product createProduct(@RequestBody Product product) {
    
            return product;
        }
    }
    

    @ApiOperation(或@Api)中的标签也可以跨控制器工作,即用给定标签标记的不同控制器类(或控制器本身)中的方法将组合在一起。

    【讨论】:

    • @SupunWijerathne 使用标签更新了答案
    • 第二个要好得多。能够在没有多个案卷定义的情况下实现它是一个巨大的胜利。感谢你的付出。希望你也从中有所收获。 :))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多