Swagger2
前后端分离
前后端分离时代:
- 后端:后端控制层,服务层,数据访问层
- 前端:前端控制层,视图层
- 伪后端数据,json数据写死,不需要后端,前端工程依旧能跑起来
- 前后端如何交互=》API
- 前后端相对独立,松耦合
- 前后端甚至可以部署在不同的服务器上
产生一个问题:
- 前后端集成联调,前端人员和后端人员无法做到
解决方案:
- 首先指定schema[计划的提纲],实时更新最新的API,降低集成的风险;
- 前后端分析:
- 前端测试后端接口:postman
- 后端提供接口,需要实时更新最新的消息及改动
Swagger简介
- 号称世界上最流行的API框架
- RestFul API文档在线自动生成工具=》API文档与API定义同步更新
- 直接运行
- 支持多种语言
Swagger使用
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiImplicitParams:多个请求参数
@ApiImplicitParam:一个请求参数
@ApiResponses:HTTP响应整体描述
@ApiResponse:HTTP响应其中1个描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiIgnore:使用该注解忽略这个API
-
添加依赖swagger2、swagger-ui
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
-
配置文件
@Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket customDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //RequestHandlerSelectors配置要扫描接口的方式 //.basepackage:指定要扫描的包 //any()S:扫描全部 .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { //作者信息 Contact contact = new Contact("团队名", "www.my.com", "my@my.com"); return new ApiInfoBuilder() .title("文档标题") .description("文档描述") .contact(contact) // 联系方式 .version("1.1.0") // 版本 .build(); } }
-
添加注释
@Api(tags = "样例接口") @RestController public class DemoController { @ApiOperation(value = "插入demo") @PutMapping("putDemo") public Map<String,Object> putDemo() { System.out.println("执行插入数据"); Map<String,Object> map = new HashMap<>(); map.put("code",200); map.put("msg","success"); return map; } @ApiOperation(value = "查询demo") @ApiImplicitParam(dataType = "integer",defaultValue = "",required = true) @GetMapping("/getDemo/{userId}") public List<String> getDemo(@PathVariable Integer userId) { List<String> list = new ArrayList<>(); list.add("OK"); return list; } }
-
浏览器访问http://localhost:8080/swagger-ui.html
-
扩展:获取当前生产环境,页面展示或不展示
public class SwaggerConfig{ @Bean public Docket docket(Environment environment){ //设置要显示的Swagger环境 Profiles profiles = Profiles.of("dev","test"); boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(flag)//enable是否启动swagger,为false则浏览器中不能访问swagger .select() .apis(RequestHandlerSelectors.basePackage("com.controller")) .build(); } //配置swagger信息=apiInfo private ApiInfo apiInfo(){ //作者信息 Contact contact = new Contact("团队名", "www.my.com", "my@my.com"); return new ApiInfoBuilder() .title("文档标题") .description("文档描述") .contact(contact) // 联系方式 .version("1.1.0") // 版本 .build(); } }
分组
每个docket实例管理一个API文档
public class SwaggerConfig{
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2.groupName("A"));
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2.groupName("B"));
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2.groupName("C"))
}
}
swagger实例说明
@ApiOperation(value = "查询所有车辆信息",notes = "成功返回pageInfo、code=200和message='查询所有车辆信息成功!',失败返回code=500和message='查询所有车辆信息失败!'")
@RequestMapping(value = "/cars", method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNow", value = "当前页数", dataType = "Integer", required = false),
@ApiImplicitParam(name = "carLike", value = "查询关键词", required = false),
@ApiImplicitParam(name = "findType", value = "查询类型:1为车牌号,2为品牌,3为型号", dataType = "Integer", required = false)
})
public Map<String, Object> findAllCars(Integer pageNow, String carLike, Integer findType) {
Map<String, Object> map = new HashMap<>();
List<Car> list = null;
try {
if (pageNow == null) {
pageNow = 1;
}
if (carLike == null || carLike.length() == 0) {
list = carService.findAllCars(pageNow);
} else {
list = carService.findCarByLike(pageNow, findType, carLike);
}
PageInfo<Car> carPageInfo = new PageInfo<>(list);
map.put("code", 200); //说明执行成功
map.put("message", "查询所有车辆信息成功!"); //展示执行信息
map.put("pageInfo", carPageInfo);
} catch (Exception e) {
map.put("code", 500); //说明执行失败
map.put("message", "查询所有车辆信息失败!");
}
return map;
}
@ApiOperation(value = "根据id查询车辆详情",notes = "成功返回car、code=200和message='查询车辆信息成功!',失败返回code=500和message='查询车辆信息失败!'")
@RequestMapping(value = "/carInfo", method = RequestMethod.GET)
@ApiImplicitParam(name = "cid",value = "车辆id", dataType = "Integer", required = true)
public Map<String, Object> findInfoByCid(Integer cid) {
Map<String, Object> map = new HashMap<>();
try {
Car car = carService.finOneCarById(cid);
map.put("car", car);
map.put("code", 200);
map.put("message", "查询车辆信息成功!");
} catch (Exception e) {
map.put("code", 500);
map.put("message", "查询车辆信息失败!");
}
return map;
}