赞
踩
swagger能够发现controller控制类内方法,能够识别出前后端交互传递的参数,并且在swaggerUI中能够触发事件进行获取数据。
下面是springboot配置swagger2的步骤:
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
package com.guli.edu.config; @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket webApiConfig(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("webApi") .apiInfo(webApiInfo()) .select() .paths(Predicates.not(PathSelectors.regex("/admin/.*"))) .paths(Predicates.not(PathSelectors.regex("/error.*"))) .build(); } @Bean public Docket adminApiConfig(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("adminApi") .apiInfo(adminApiInfo()) .select() .paths(Predicates.and(PathSelectors.regex("/admin/.*"))) .build(); } private ApiInfo webApiInfo(){ return new ApiInfoBuilder() .title("网站-课程中心API文档") .description("本文档描述了课程中心微服务接口定义") .version("1.0") .contact(new Contact("Helen", "http://atguigu.com", "55317332@qq.com")) .build(); } private ApiInfo adminApiInfo(){ return new ApiInfoBuilder() .title("后台管理系统-课程中心API文档") .description("本文档描述了后台管理系统课程中心微服务接口定义") .version("1.0") .contact(new Contact("Helen", "http://atguigu.com", "55317332@qq.com")) .build(); } }
在如上配置中,使swagger有了过滤controller类的功能,能够实现admin和普通请求的区分。
自定义设置是为了让我们在swaggerUI进行事件触发模拟时,使返回结果拥有默认样例,方便在swaggerUI中理解数据类型,例如:
@ApiModelProperty(value = "创建时间", example = "2019-01-01 8:00:00")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间", example = "2019-01-01 8:00:00")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
接下来是定义接口说明和参数说明:
@Api(description="讲师管理") @RestController @RequestMapping("/admin/edu/teacher") public class TeacherAdminController { @Autowired private TeacherService teacherService; @ApiOperation(value = "所有讲师列表") @GetMapping public List<Teacher> list(){ return teacherService.list(null); } @ApiOperation(value = "根据ID删除讲师") @DeleteMapping("{id}") public boolean removeById( @ApiParam(name = "id", value = "讲师ID", required = true) @PathVariable String id){ return teacherService.removeById(id); } }
定义接口说明和参数说明实现效果如下:
swagger是一个非常方便的,适用于测试后端传递数据的一个框架,集成和配置起来非常方便。掌握swagger是使自己掌握全栈的重要方法!希望这篇文章能对你有小小的帮助,我是黑马Jack,感谢你的阅读,一起学习一起进步!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。