代码之家  ›  专栏  ›  技术社区  ›  Supun Wijerathne

按资源分组的端点Swagger注释?

  •  0
  • Supun Wijerathne  · 技术社区  · 8 年前

    我正在使用Spring开发RESTAPI。我有一些API,其中有很多端点。当我打开招摇过市的用户界面时,它看起来很拥挤。

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

    我只想知道如何通过Spring的自大注释来实现这一点。如果有人能举个例子来描述,我将不胜感激。

    另外,我想知道我们是否可以重新组合(更高级别的分组)我们用上面的方式推断出的分组?

    1 回复  |  直到 8 年前
        1
  •  6
  •   Supun Wijerathne    8 年前

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

    定义多个 Docket bean用于每个组,而u将根据需要获得逻辑分组。

    @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();
    }
    

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

    groups

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

    您不需要定义多个 只要一粒就够了。

    @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 (在方法级别,将重写类级别的值)。

    @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;
        }
    }
    

    tags

    标签 @A操作 (或) @ Api )也将在控制器之间工作,即使用给定标记标记的不同控制器类(或控制器本身)中的方法将被分组在一起。