1.引入依赖
<!--Swagger-ui 图形化接口-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui ->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
2.添加配置类
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; // 启动时加载类 @Configuration // 启用Swagger API文档 @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 自行修改为自己的包路径 .apis(RequestHandlerSelectors.basePackage("com.zp.springbootdemo.system.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("客户管理") .description("客户管理中心 API 1.0 操作文档") .version("1.0") .build(); } }
3.Swagger常用注解
| 作用范围 | API | 使用位置 |
|---|---|---|
| 协议集描述 | @Api | 用于 Controller 类上 |
| 协议描述 | @ApiOperation | 用在 Controller 的方法上 |
| 非对象参数集 | @ApiImplicitParams | 用在 Controller 的方法上 |
| 非对象参数描述 | @ApiImplicitParam | 用在 @ApiImplicitParams 的方法里边 |
| 响应集 | @ApiResponses | 用在 Controller 的方法上 |
| 响应信息参数 | @ApiResponse | 用在 @ApiResponses 里边 |
| 描述返回对象的意义 | @ApiModel | 用在返回对象类上 |
| 对象属性 | @ApiModelProperty | 用在出入参数对象的字段上 |
@Api的使用
API作用在Controller,作为swagger文档资源,该注解将一个controller标注为一个Swagger资源(API). 在默认情况下,Swagger-Core 只会扫描解析具有 @Api 注解的类,而会自动忽略其他类别资源(JAX-RS endpoints、Servlets 等)的注解。
@Api(value = "用户信息",description = "用户操作 API", position = 100, protocols = "http") @RestController @RequestMapping("/user") public class UserController{ }
启动项目,访问http://localhost:8080/swagger-ui.html#/message-controller 就可以看到效果,自动将MessageController内的方法都添加映射,并标明了每种方法的请求方式
@ApiOperation 的使用
ApiOperation 定义在方法上,描述方法名、方法解释、返回信息、标记等信息。
| 属性名称 | 备注 |
|---|---|
| value | url 的路径值 |
| tags | 如果设置这个值,value 的值会被覆盖 |
| description | 对 API 资源的描述 |
| produces | For example, "application/json, application/xml" |
| consumes | For example, "application/json, application/xml" |
| protocols | Possible values: http, https, ws, wss |
| authorizations | 高级特性认证时配置 |
| hidden | 配置为 true 将在文档中隐藏 |
| response | 返回的对象 |
| responseContainer | 这些对象是有效的 "List", "Set" or "Map",其他无效 |
| httpMethod | "GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"OPTIONS" and "PATCH" |
| code | http 的状态码 默认 200 |
| extensions | 扩展属性 |
@ApiOperation(value = "/获取用户信息",notes = "根据id获取用户信息",httpMethod = "POST") @PostMapping("/getUser") public JSONObject getUser(@RequestBody JSONObject user){ }
@ApiImplicitParams 和 @ApiImplicitParam 的使用
@ApiImplicitParams 用于描述方法的返回信息,和 @ApiImplicitParam 注解配合使用;@ApiImplicitParam 用来描述具体某一个参数的信息,包括参数的名称、类型、限制等信息。
@ApiOperation(
value = "添加信息",
notes = "根据传递的参数创建信息"
)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "消息ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "text", value = "消息正文", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),
})
@PostMapping(value = "message")
public Message create(Message message) {
message = this.messageRepository.save(message);
return message;
}
| 属性名称 | 备注 |
|---|---|
| name | 接收参数名 |
| value | 接收参数的意义描述 |
| required | 参数是否必填值为 true 或者 false |
| dataType | 参数的数据类型只作为标志说明,并没有实际验证 |
| paramType | 查询参数类型,其值: path 以地址的形式提交数据 query 直接跟参数完成自动映射赋 body 以流的形式提交,仅支持 POST header 参数在 request headers 里边提交 form 以 form 表单的形式提交 仅支持 POST |
@ApiResponses 和 @ApiResponse 的使用
@ApiResponses 主要封装方法的返回信息和 @ApiResponse 配置起来使用,@ApiResponse 定义返回的具体信息包括返回码、返回信息等。
@ApiOperation(value = "修改信息", notes = "根据参数修改信息") @ApiResponses({ @ApiResponse(code = 100, message = "请求信息有误"), @ApiResponse(code = 101, message = "未授权"), @ApiResponse(code = 103, message = "禁止访问"), @ApiResponse(code = 104, message = "请求路径不存在"), @ApiResponse(code = 200, message = "服务器内部错误"), }) @PutMapping(value = "message") public Message modify(Message message) { Message messageResult=this.messageRepository.update(message); return messageResult; }
| 属性名称 | 备注 |
|---|---|
| code | http 的状态码 |
| message | 描述 |
| response | 默认响应类 Void |
| reference | 参考 |
| responseHeaders | 封装返回信息 |
| responseContainer | 字符串 |
@ApiModel 和 @ApiModelProperty 的使用
在实际的项目中我们常常会封装一个对象作为返回值,@ApiModel 就是负责描述对象的信息,@ApiModelProperty 负责描述对象中属性的相关内容。
@ApiModel(description = "响应对象")
public class BaseResult<T> {
private static final int SUCCESS_CODE = 0;
private static final String SUCCESS_MESSAGE = "成功";
@ApiModelProperty(value = "响应码", name = "code", required = true, example = "" + SUCCESS_CODE)
private int code;
@ApiModelProperty(value = "响应消息", name = "msg", required = true, example = SUCCESS_MESSAGE)
private String msg;
@ApiModelProperty(value = "响应数据", name = "data")
private T data;
private BaseResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
private BaseResult() {
this(SUCCESS_CODE, SUCCESS_MESSAGE);
}
private BaseResult(int code, String msg) {
this(code, msg, null);
}
private BaseResult(T data) {
this(SUCCESS_CODE, SUCCESS_MESSAGE, data);
}
public static <T> BaseResult<T> success() {
return new BaseResult<>();
}
public static <T> BaseResult<T> successWithData(T data) {
return new BaseResult<>(data);
}
public static <T> BaseResult<T> failWithCodeAndMsg(int code, String msg) {
return new BaseResult<>(code, msg, null);
}
public static <T> BaseResult<T> buildWithParam(ResponseParam param) {
return new BaseResult<>(param.getCode(), param.getMsg(), null);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static class ResponseParam {
private int code;
private String msg;
private ResponseParam(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResponseParam buildParam(int code, String msg) {
return new ResponseParam(code, msg);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
}
@PatchMapping(value="/message/text") public BaseResult<Message> patch(Message message) { Message messageResult=this.messageRepository.updateText(message); return BaseResult.successWithData(messageResult); }
| 属性名称 | 备注 |
|---|---|
| value | 属性描述 |
| name | 如果配置覆盖属性名称 |
| allowableValues | 允许的值 |
| access | 可以不配置 |
| notes | 没有使用 |
| dataType | 数据类型 |
| required | 是否为必传参数 |
| position | 显示的顺序位置 |
| hidden | 是否因此 |
| example | 举例 |
| readOnly | 只读 |
| reference | 引用 |
4.启动项目,进入API列表,查看地址:http://127.0.0.1:8080/swagger-ui.html
