本身用于管理接口的一种注解,添加后项目启动可以在指定页面访问到已添加归类的所有 API 接口
需要引入相关的 swagger 依赖,类似如下
<dependency>
<groupId>io.swaggergroupId>
<artifactId>swagger-parserartifactId>
<version>1.0.46version>
dependency>
dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
其二 需要对Swagger 添加 配置类 (需要 spring 框架)
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
具体参考其他更详细的配置,这里我太菜就不多说了
一般 controller 上如下示例:
@Api(value = "标题", tags = "标签一", description = "描述")
public class xxxxxxxxxxxController {
..............
}
@Api 用在总的 controller 上方
value 即名称,也可以默认不写value ,默认会给与 value 例如
@Api("标题")
tags 即对 api 的分类,类似于接口的标签用于进一步分类
description 即对接口的描述
一般接口上如下示例
@ApiOperation(value = "查看具体详情", httpMethod = "GET", consumes = "application/json", produces = "application/json")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "唯一标识", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String", paramType = "query")})
@ApiResponses({
@ApiResponse(code = 2000, message = "success", response = Response.class),
@ApiResponse(code = 2004, message = "auth Fail", response = Response.class)}
)
@GetMapping("/userApplication/details")
public Response getDetails(HttpServletRequest request, @RequestParam(value = "userId") Long userId,
@RequestParam(value = "deptId") Long deptId,
@RequestParam(value = "id") Long id,
@RequestParam(value = "password", required = false) String password) {
............................
}
@ApiOperation :
对当前具体接口的描述, value 即标题, httpMethod 请求类型
@ApiImplicitParams:
接口的入参,内部是一个数组的形式
@ApiImplicitParam:
上面注解内单个入参的声明方式,name 参数名, value 对参数的说明,required 该参数是否必须, dataType 数据类型 大小写不唯一, paramType 参数类型
@ApiResponses:
接口响应说明
@ApiResponse
上面单个响应的声明方式,code 响应code(注意并不是HTTP请求code而是自己定义的返回code),message 返回信息, response 返回的类型,也可以说响应的类型(这里Response 是自己定义的一种响应类, 基本包括 code, message, data )
如果只有一个入参或者响应也可以不用 @ApiImplicitParams 或 @ApiResponses
可以直接使用 @ApiImplicitParam 以及 @ApiResponse 一般都使用复数形式使得保持一致
说明:
由于数据库获取的实体实际上我们并不完全给到API 响应的实体定义当中或者说有时候是不全的,所以就多了很多 VO BO POJO DTO Model等等,实际上的数据数量相差有时候并不多或者很多时常常会这样处理,控制接口的返回结果,或者使用 该model 控制post 的入参类型的定义
一般返回接口的内容同样可以给到 swagger 中,使得对接接口的人了解到当前接口的入参或者返回值中 该model 所有属性的说明和具体意义
swagger 对于 model 的注解示例如下:
@ApiModel("一个Model定义")
public class AppModel {
@ApiModelProperty(value = "id")
private String id;
@ApiModelProperty(value = "名称")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModel:
用于对接口定义的页面识别或者接受的类上,认为这是一个需要 在 swagger 上展示说明的类
@ApiModelProperty:
对单个属性的说明 value 即说明,其实还有很多 具体要看注解内部的定义属性,都可以添加