swagger接口测试
1.导入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
2.yml配置
server:
port: 9090 #端口号
logging:
level:
com.wn.book.controller: debug #日志
knife4j:
enable: true #此项必配置,否则knife4j运行有问题
3.书写Controller
@Api(tags = "图书管理")
@RestController
@RequestMapping("api")
@Slf4j
public class BookController {
private int a;
@Autowired
private QiangGou qiangGou;
@ApiOperation(value = "findAll", notes = "查询图书类型接口")
@GetMapping("findAll")
public HttpResp findAll() {
/*List<Type> list = new ArrayList<>(20);
for (int i = 1; i <= 100; i++) {
list.add(new Type(i, "type_" + i, "admin", new Date(), new Date()));
}
log.debug("查询所有图书类型数量:{}", list.size());
return new HttpResp<>(200, "查询成功", list, LocalDate.now());*/
a = a + 1;
log.debug("查询所有图书类型数量:{}", a);
return new HttpResp<>(200, "查询成功", a, LocalDate.now());
}
@ApiOperation(value = "addType", notes = "添加新图书类型接口")
@ApiImplicitParams({@ApiImplicitParam(name = "name", value = "请输入新图书类型名称", required = true)})
@PostMapping("addType")
public HttpResp addType(String name) {
log.debug("添加新的类型:{}", name);
return new HttpResp<>(200, "添加成功", name, LocalDate.now());
}
@ApiOperation(value = "uploadExcel", notes = "上传excel文件进行解析")
@ApiImplicitParams({@ApiImplicitParam(value = "上传文件", required = true)})
@PostMapping("uploadExcel")
public HttpResp uploadExcel(MultipartFile excel) {
String filename = excel.getOriginalFilename();
log.debug("上创文件名称:{}", filename);
return new HttpResp<>(200, "成功", filename + "上传成功", LocalDate.now());
}
@ApiOperation(value = "qiang", notes = "抢购")
@PutMapping("qiang")
public HttpResp qiang(){
try {
int qiang = qiangGou.qiang();
log.debug("书还剩余:{}",qiang);
return new HttpResp<>(200, "抢购成功", qiang, LocalDate.now());
}catch (Exception e){
return new HttpResp<>(200, "书已卖完", -1, LocalDate.now());
}
}
}
1 @Api(tags = “Knife4jController接口类”)
2 @Api 修饰整个类,描述api(Controller)的作用
3 @ApiOperation 描述一个类的一个方法,或者说一个接口
4 @ApiImplicitParam 多个请求参数的描述信息
5 @ApiImplicitParam(name = “name”,value=”请求的名称”,required = true) 单个参数的描述信息
6 @ApiIgnore 使用该注解忽略这个API
7 @ApiError 发生错误返回的信息
Type类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Type {
private Integer id;
private String name;
private String updateBy;
private Date createTime;
private Date updateTime;
}
HttpResp返回结果
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HttpResp<T> {
private int code;
private String msg;
private T data;
private LocalDate time;
}
4.测试(浏览器输入)
http://localhost:9090/doc.html