前面我们记录了如何整合swagger2插件,本篇主要介绍插件的配置及注释说明。
Swagger2配置文件说明
直接上加了注释的代码,看代码更清晰:
@Configuration
//@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket systemManagerApi() {
return new Docket(DocumentationType.SWAGGER_2)
//获取接口信息
.apiInfo(getApiInfo())
//指定主机域名
.host("https://www.baidu.com/")
//分组
.groupName("systemManager")
.select()
//-------- 指定扫描那些接口 --------
//扫描所有
//.apis(RequestHandlerSelectors.any())
//扫描所有有注解的api
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//扫描指定位置
.apis(RequestHandlerSelectors.basePackage("stu.up2uper.springstu.controller"))
//-------- 指定扫描路径 --------
.paths(PathSelectors.any())
.build();
}
@Bean
public Docket systemAppApi() {
return new Docket(DocumentationType.SWAGGER_2)
//获取接口信息
.apiInfo(getApiInfo())
//分组
.groupName("systemApp")
.select()
//-------- 指定扫描那些接口 --------
//扫描所有
//.apis(RequestHandlerSelectors.any())
//扫描所有有注解的api
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//扫描指定位置
.apis(RequestHandlerSelectors.basePackage("stu.up2uper.springstu.controller"))
//-------- 指定扫描路径 --------
.paths(PathSelectors.any())
.build();
}
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
//标题
.title("系统接口文档")
//描述
.description("此文档为系统接口说明,配置及相关注解")
//许可证
.license("Swagger api 2022/16/01")
//许可证地址
.license("https://www.github.com")
//服务条款地址
.termsOfServiceUrl("https://www.spring.io")
//版本
.version("1.0.0")
//维护人信息
.contact(new Contact("hunkxia", "https://blog.youkuaiyun.com/hunkxia", "hunk.xia@gmail.com"))
.build();
}
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
}
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
}
通过配置,我们可以对接口进行分组展示,并且能指定扫描路径,最后呈现的UI如下:

常见注释说明及用法
swagger2内置了许多注释,来方便开发人员实现接口注释功能,常见注释标签如下:

其中一些标签的参数都已过时,以下只展示常见标签的说明:
| 标签 | 使用位置 | 描述 |
|---|---|---|
| @Api | Controller | 请求类说明 |
| @ApiIgnore | Controller | 隐藏说明,无需参数 |
| @ApiParam | Method | 方法参数说明 |
| @ApiImplicitParam | Method | 方法单个参数说明 |
| @ApiImplicitParams | Method | 方法参数的说明 |
| @ApiResponse | Method | 单个返回状态码说明 |
| @ApiResponses | Method | 方法返回状态码说明 |
| @ApiModel | Model | 实体类说明 |
| @ApiModelProperty | Model属性 | 实体类属性说明 |
| @JsonIgnore | Model属性 | 隐藏说明 |
| @ApiOperation | Method | 方法说明 |
- @api标签说明:
| 标签 | 说明 |
|---|---|
| tags | 标题描述,支持多个标题 |
| produces | 生产者,输出什么内容,如"application/json, application/xml" |
| consumes | 消费者,输入什么内容,如上 |
| protocols | 请求协议规则 |
| authorizations | 安全设置 |
| hidden | 是否隐藏 |
- @ApiParam标签说明:
一般写在方法参数上如下:
@RequestMapping(value = "listByPage", method = RequestMethod.GET)
@ResponseBody
public List<G2AdminRoleAccess> getRolesByPage(
@ApiParam(value = "页码") @RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "size", defaultValue = "10") int size){
return roleAccessService.listRole(page, size);
}
具体参数
| 标签 | 说明 |
|---|---|
| name | 名称 |
| value | 字段描述 |
| defaultValue | 默认值 |
| allowableValues | 可允许值 |
| required | 是否必须 |
| allowMultiple | 是否为集合 |
| dataType | 参数数据类型,int、float、String等等 |
| dataTypeClass | 参数指定类类型 |
| paramType | 参数类型,包括path、query、body、header、form |
| example | 举例 |
| Example | 实体类举例 |
| allowEmptyValue | 是否可为空 |
| readOnly | 是否只读 |
- @ApiImplicitParam标签说明:
与上方ApiParam一样,只不过注释的位置不一样,如下:
@RequestMapping(value = "addRole", method = RequestMethod.POST)
@ApiImplicitParam(name = "role", value = "权限信息", dataTypeClass = G2AdminRoleAccess.class, required = true)
public int addRole(@RequestBody G2AdminRoleAccess role){
return roleAccessService.addRole(role);
}
- @ApiImplicitParams标签说明:
包括多个ApiImplicitParam整合,不再描述,直接给个列子:
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam()
})
public List<G2AdminRoleAccess> getRoles(){
return roleAccessService.listAllRole();
}
- @ApiResponse标签说明:
用于描述返回值状态码,主要的参数如下:
| 标题 | 说明 |
|---|---|
| code | 返回码 |
| message | 返回消息 |
| response | 抛出异常的类 |
| responseHeaders | 定义响应头 |
参考如下:
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam()
})
@ApiResponse(code = 200, message = "返回正常")
public List<G2AdminRoleAccess> getRoles(){
return roleAccessService.listAllRole();
}
- @ApiResponses标签说明:
支持多个ApiResponse标签。
@RequestMapping(value = "addRole", method = RequestMethod.POST)
@ApiImplicitParam(name = "role", value = "权限信息", dataTypeClass = G2AdminRoleAccess.class, required = true)
@ApiResponses({
@ApiResponse(code = 200, message = "返回正常"),
@ApiResponse(code = 404, message = "请求路径不存在"),
})
public int addRole(@RequestBody G2AdminRoleAccess role){
return roleAccessService.addRole(role);
}
- @ApiModel标签说明:
| 标签 | 说明 |
|---|---|
| value | 标题 |
| description | 描述 |
| parent | 所属父类 |
@ApiModel(value = "用户角色", description = "用户角色信息")
public class G2AdminRoleAccess implements Serializable {
}
- @ApiModelProperty模型属性标签:
| 标签 | 说明 |
|---|---|
| value | 标题 |
| allowableValues | 可允许值 |
| dataType | 数据类型 |
| required | 是否必须 |
| position | 排序位置 |
| readOnly | 是否只读 |
| allowEmptyValue | 是否为空 |
举例:
@ApiModel(value = "用户角色", description = "用户角色信息")
public class G2AdminRoleAccess implements Serializable {
private Integer id;
/**
* 角色ID
*
* @mbg.generated
*/
@ApiModelProperty(value = "角色ID")
private Integer roleId;
}
- @JsonIgnore标题说明:
与ApiModelProperty标签中的hidden类似,无参数,表示隐藏此属性。
- @ApiOperation标签说明:
此标签主要用来描述方法的具体说明,主要有以下参数:
| 标签 | 说明 |
|---|---|
| value | 对方法简单说明 |
| notes | 对方法详细说明 |
| tags | 标题,支持多组标题 |
| responseContainer | 响应容器 |
| httpMethod | 请求方法类型 |
| hidden | 是否隐藏此方法 |
| code | 状态码 |
| produces | 生产者,输出格式,如application/json, application/xml |
| consumes | 消费者,输入格式 |
代码如下:
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam()
})
@ApiOperation(value = "获取角色所有类型", tags = {"获取角色", "所有角色"})
@ApiResponse(code = 200, message = "返回正常")
public List<G2AdminRoleAccess> getRoles(){
return roleAccessService.listAllRole();
}
@RequestMapping(value = "listByPage", method = RequestMethod.GET)
@ResponseBody
public List<G2AdminRoleAccess> getRolesByPage(
@ApiParam(value = "页码") @RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "size", defaultValue = "10") int size){
return roleAccessService.listRole(page, size);
}
至此上面介绍了常见的标签,大部分情况下够用了,以下贴出全部代码。
controller类代码:
@Controller
@RequestMapping("/yx-user")
@Api(tags = {"用户模块"})
public class YxUserController {
@Autowired
private RoleAccess roleAccessService;
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({
@ApiImplicitParam()
})
@ApiOperation(value = "获取角色所有类型", tags = {"获取角色", "所有角色"})
@ApiResponse(code = 200, message = "返回正常")
public List<G2AdminRoleAccess> getRoles(){
return roleAccessService.listAllRole();
}
@RequestMapping(value = "listByPage", method = RequestMethod.GET)
@ResponseBody
public List<G2AdminRoleAccess> getRolesByPage(
@ApiParam(value = "页码") @RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "size", defaultValue = "10") int size){
return roleAccessService.listRole(page, size);
}
@RequestMapping(value = "addRole", method = RequestMethod.POST)
@ApiImplicitParam(name = "role", value = "权限信息", dataTypeClass = G2AdminRoleAccess.class, required = true)
@ApiResponses({
@ApiResponse(code = 200, message = "返回正常"),
@ApiResponse(code = 404, message = "请求路径不存在"),
})
public int addRole(@RequestBody G2AdminRoleAccess role){
return roleAccessService.addRole(role);
}
}
model类代码:
@ApiModel(value = "用户角色", description = "用户角色信息")
public class G2AdminRoleAccess implements Serializable {
private Integer id;
/**
* 角色ID
*
* @mbg.generated
*/
@ApiModelProperty(value = "角色ID")
private Integer roleId;
}
总体来说swagger2代码还是容易理解,如果遇到问题,可以下载源代码看下其中的英文描述。此篇文章是针对单个应用集成的,对于多应用微服务,接口相对较繁杂,在架构中我们需要提前就要划分好模块,使得后面开发起来更便捷。在下一篇中我们来研究一下如何实现微服务下整合swagger2。

本文详细介绍Swagger2配置,包括接口分组、路径选择、注释标签的使用,帮助开发者快速创建和管理API文档。涵盖了@Api、@ApiParam等常见注解的详细说明和示例。
2009





