端点按资源大笔标注进行分组?

Sup*_*hne 1 api rest spring swagger springfox

我将Spring用于我的REST API开发。我有一些端点很多的API。当我打开swagger ui时,它看起来很拥挤。

我刚刚读了这篇文章,发现可以根据资源级别对端点进行分组。

我只想知道如何使用Spring的大笔注解来实现。我很高兴有人可以举例说明。

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

Pra*_*tel 10

********** 解决方案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();
}
Run Code Online (Sandbox Code Playgroud)

现在,您将在下面的swagger ui中得到两个组。

团体

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

您不需要定义多个Docketbean,只需定义一个就足够了。

@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();
}
Run Code Online (Sandbox Code Playgroud)

之后,您只需使用@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

标签

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

  • 第二个要好得多。能够在没有多个案卷定义的情况下实现它是一个巨大的胜利。感谢你的付出。希望你也能从中有所收获。:)) (2认同)