我正在使用Spring进行REST API开发。我有一些有很多端点的API。当我打开swagger ui时,它看起来像是打包的。
我刚刚读了this的文章,看到我们可以根据资源级别对端点进行分组。
我只想知道如何使用Spring的swagger注解来实现这一点。如果有人能举个例子来描述,我将不胜感激。
我还想知道我们是否可以重新组织(更高级别的分组),我们用上面的方式推导出的组?
发布于 2018-05-28 22:27:39
*方案一:(使用群组)*
只需为每个组定义多个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 ui中获得两个组,如下所示。

*方案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)中的标签也可以跨控制器工作,即用给定标签标记的不同控制器类(或控制器本身)中的方法将被分组在一起。
https://stackoverflow.com/questions/50567317
复制相似问题