一,swagger2简单介绍
在前后端分离开发模式中,api文档是最好的沟通方式。而Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
1,在成在线的api文档
2,直接在接口文档上进行测试,以方便理解业务
3,文档会显示:接口的地址,请求方式,参数,响应格式和错误信息
二,配置Swagger2
1,引入swagger的依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
2,需要编写配置类
@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("本文档描述了xxx微服务接口定义")
.version("1.0")
.contact(new Contact("java", "http://baidu.com", "1123@qq.com"))
.build();
}
}
三,操作测试
1,在启动类上添加注解,扫描swagger配置类所在的包
@ComponentScan(basePackages = {"com.gp"})
2,我这Controller里有一查询和一个删除方法
3,启动程序,输入网址:http://localhost:9090/swagger-ui.html
效果:
四,Swagger 相关注解
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiIgnore:使用该注解忽略这个API
@ApiImplicitParam:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值
@ApiImplicitParams:描述由多个 @ApiImplicitParam 注解的参数组成的请求参数列表
@ApiResponses:HTTP响应整体描述
@ApiError :发生错误返回的信息
@ApiResponse:HTTP响应其中1个描述
应用Controller层
@RestController
@Api(tags={"这是一个controller","哈哈哈"})
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService teacherService;
@ApiOperation(value="删除操作", notes="删除object", produces="application/json")
@DeleteMapping("{id}")
public boolean removeById(@PathVariable String id){
return teacherService.removeById(id);
}
}
上述效果: