一.Swagger2介绍
前后端分离开发模式中,api文档是最好的沟通方式。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
1.及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
2.规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
3.一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
4.可测性 (直接在接口文档上进行测试,以方便理解业务)
二.配置Swagger2
1.创建模块,为了让其他功能微服务对其依赖
注意对其依赖后需要在微服务的主启动类上配置扫描Swagger2的配置类
2.引入依赖
<!--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>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.2</version>
</dependency>
3.编写配置类
@Configuration
@EnableSwagger2//开启swagger支持
public class Swagger2Config {
//对不同路径进行分类显示
@Bean
public Docket adminApiConfig(){
return new Docket(DocumentationType.SWAGGER_2).groupName("admin").apiInfo(adminApiInfo()).select().paths(PathSelectors.regex("/admin/.*")).build();
}
@Bean
public Docket userApiConfig(){
return new Docket(DocumentationType.SWAGGER_2).groupName("userApi").apiInfo(userApiInfo()).select().paths(PathSelectors.regex("/user/.*")).build();
}
private ApiInfo adminApiInfo(){
return new ApiInfoBuilder().title("管理员系统Api文档").version("v1.0").build();
}
private ApiInfo userApiInfo(){
return new ApiInfoBuilder().title("用户系统Api文档").version("v1.0").build();
}
}
5.通过注解标注访问接口.携带参数等
对接口的定义
//医院设置接口
@Api(tags = "医院设置接口")
@RestController
@RequestMapping("/admin/hosp/hospitalSet")
public class HospitalSetController {
@Autowired
private HospitalSetService hospitalSetService;
//查询所有医院设置
@ApiOperation(value = "医院设置列表")
@GetMapping("findAll")
public List<HospitalSet> findAll() {
List<HospitalSet> list = hospitalSetService.list();
return list;
}
@ApiOperation(value = "医院设置删除")
@DeleteMapping("{id}")
public boolean removeById(@ApiParam(name = "id", value = "医院设置ID", required = true) @PathVariable String id){
return hospitalSetService.removeById(id);
}
}
对pojo类的定义,设置请求的样例数据
@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;
6.通过地址访问测试
8201/doc.html
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(new ApiInfoBuilder().title("微信支付接口文档案例").build());
}