一、Swagger2的作用
手写Api文档的几个痛点:
- 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
- 接口返回结果不明确
- 不能直接在线测试接口,通常需要使用工具,比如postman
- 接口文档太多,不好管理
Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。
二、pom依赖:springfox-swagger2、springfox-swagger-ui
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
三、Swagger2配置类
@Configuration
@EnableSwagger2 //开启Swagger2
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("0.0.1-SNAPSHOT")
.contact(new Contact("java","http://atguigu.com","123456@qq.com"))
.build();
}
}
有这两步就已经完成swagger的基本功能,可以访问http://localhost:{port}/swagger-ui.html,来实现调用controller中的接口。如
但实际上,我们依然可以给controller的类、接口、接口入参添加注解, 以实现功能说明的作用。
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数
四、Controller类添加Swagger的注解
@Api(description = "讲师管理") //修饰整个类,描述Controller的作用
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
@Autowired
private EduTeacherService eduTeacherService;
@ApiOperation("查找全部功能")
@GetMapping("/findall")
public List<EduTeacher> findAll(){
List<EduTeacher> list = eduTeacherService.list();
return list;
}
@ApiOperation("逻辑删除功能")
@DeleteMapping("{id}") //{id}表示id值通过路径传递
public void removeById(@PathVariable("id") String id){
eduTeacherService.removeById(id);
}
}
再次访问Swagger-ui,效果如下
五、整合Swagger3配置类
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
//PathSelectors.regex("/error.*")选择器,negate()表示取反
.paths(PathSelectors.regex("/error.*").negate())
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("在线教育API文档")
.description("本文档描述了在线教育微服务接口定义")
.version("1.0-SNAPSHOT")
.build();
}
}