@TOC
1、swagger基本概念
按照它的规范去定义接口及接口相关的信息
通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多种语言的客户端和服务端的代码,以及在线接口调试页面等等
Springfox
所以作为Java届服务端的大一统框架Spring,迅速将Swagger规范纳入自身的标准,建立了Spring-swagger项目,后面改成了现在的Springfox
通过在项目中引入Springfox,可以扫描相关的代码,生成该描述文件,进而生成与代码一致的接口文档和客户端代码。这种通过代码生成接口文档的形式,在后面需求持续迭代的项目中,显得尤为重要和高效
2、操作
依赖
结构
把项目的基本结构搭建好
注解
在controller类添加@Api(value="用户业务控制器",tags=("用于用户业务的处理")
方法添加注解@ApiOperation("value= "用户登录",notes="完成用户的登录验证",httpMethod=“POST”)
notes是更具体的说明,httpMethod用来定义请求的提交方式,全大写
对方法的入参加上说明@ApiImplicitParam()
配置
必须要有config配置文件,写法是固定的
package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com"))//扫描
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("swagger测试示例")
.description("超市订单系统接口测试")
.version("1.0")
.contact(new Contact("接口文档","blog.csdn.net","aaa@gmail.com"))
.license("The Apache License")
.licenseUrl("http://www.baidu.com")
.build());
}
}
访问
启动项目,访问swagger提供的页面
访问详细信息
在dto里添加注释
@ApiModel(value = "Dto", description = "数据传输对象")
@ApiModelProperty("错误编码")
private String errorCode;
@ApiModelProperty("提示信息")
private String msg;
@ApiModelProperty("页面需要解析的数据")
private Object obj;
在控制类的注释 @ApiOperation加上response = Dto.class
/**
* 登录
* @return
*/
@ApiOperation(value = "用户登录", notes = "完成用户的登录验证", httpMethod = "POST", response = Dto.class)
@ApiImplicitParams({
@ApiImplicitParam(value = "用户名", name = "userName", required = true, dataType = "String",
paramType = "query", defaultValue = "apple"),
@ApiImplicitParam(value = "密码", name = "password", required = true, dataType = "String",
paramType = "query", defaultValue = "0000")
})
@PostMapping("/login")
@ResponseBody
public Dto login(String userName, String password){
System.out.println(">>> user login");
System.out.println(new User(userName, password));
// System.out.println(user);
//查询
List<User> userList = userService.find(new User(userName, password));
//判断, userList的大小
if (userList.size() != 1){
return DtoUtil.error("20000001", "用户名或密码错误!");
}
return DtoUtil.success(userList.get(0));
}