swagger2配置及注释详解

8 篇文章 0 订阅
5 篇文章 0 订阅

前面我们记录了如何整合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.csdn.net/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内置了许多注释,来方便开发人员实现接口注释功能,常见注释标签如下:

在这里插入图片描述
其中一些标签的参数都已过时,以下只展示常见标签的说明:

标签使用位置描述
@ApiController请求类说明
@ApiIgnoreController隐藏说明,无需参数
@ApiParamMethod方法参数说明
@ApiImplicitParamMethod方法单个参数说明
@ApiImplicitParamsMethod方法参数的说明
@ApiResponseMethod单个返回状态码说明
@ApiResponsesMethod方法返回状态码说明
@ApiModelModel实体类说明
@ApiModelPropertyModel属性实体类属性说明
@JsonIgnoreModel属性隐藏说明
@ApiOperationMethod方法说明
  • @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。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值