首先,我们先对swagger做一个介绍在现在前后端分离开发模式中,api文档是最好的沟通方式.所以swagger成了炙手可热的工具了.Swagger是一个规范的和完整的框架,用于生成,描述,调用和可视化RestFul风格的web服务.特性:及时性(接口变更后,能够及时的准确的通知相关前后端的开发人员)规范性(并且保持接口的规范性,比如说,接口的地址,请求方式,参数及其响应格式和错误信息)一致性(接口信息一致,不会出现因为开发人员拿到的版本不一致,而出现分歧)可测性(直接在接口文档上进行测试,以方便理解业务)
整合swagger进行接口测试:首先我们创建一个公共模块:以一个maven项目创建.接下来引入依赖:
io.springfox
springfox-swagger2
provided
io.springfox
springfox-swagger-ui
provided
改一下类型为pom,这里不写代码
接下来再建一个模块做为common的子模块service_bas创建包,结构如下:编写SwaggerConfig代码
package com.qiu.servicebase;
import com.google.common.base.Predicates;
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.service.ApiInfo;
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 //引入Swagger注解
public class SwaggerConfig {
@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();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title('网站-课程中心API文档')
.description('本文档描述了课程中心微服务接口定义')
.version('1.0')
.contact(new Contact('java', 'http://71953689.top', '71953689@qq.com'))
.build();
}
}
由于我们的Swager并不在同一个模块中,这么做就是好做一个全局的Swagger,所以我们可以将需要用到Swagger的地方进行配置即可比如说我们在需要引入的依赖中引入
com.qiu
service_base
0.0.1-SNAPSHOT
并且在需要用到的启动类中加上注解:
这样就整合好了,但是我们需要更友好的界面,所以我们就使用一些注解进行swagger中文化.
package com.qiu.eduservice.controller;
import com.qiu.eduservice.entity.EduTeacher;
import com.qiu.eduservice.service.EduTeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* 讲师 前端控制器
*
*
* @author qiuzhikang
* @since 2020-07-23
*/
@Api(description = '讲师管理')
@RestController
@RequestMapping('/eduservice/eduteacher')
public class EduTeacherController {
@Autowired
private EduTeacherService teacherService;
//查询所有的老师的信息,rest风格
@ApiOperation('所有讲师列表')
@GetMapping('findAll')
public List findAllTeacher(){
List list = teacherService.list(null);
return list;
}
//2.逻辑删除讲师的方法,ID需要通过路径传递,@PathVa...就是指明id为path下的
@ApiOperation('逻辑删除讲师')
@DeleteMapping('{id}')
public boolean removeTeacher(@ApiParam(name = 'id',value = '讲师ID',required = true)
@PathVariable String id){
boolean flag = teacherService.removeById(id);
return flag;
}
}
文章为作者独立观点,不代表 股票程序化软件自动交易接口观点