SpringBoot整合Swagger2,再也没有接口文档的烦恼了!
导语:
相信无论是前端还是后端开发,都或多或少地被接口文档折磨过。前端经常抱怨后端给的接口文档与实际情况不一致。后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档。但是这个接口文档对于程序员来说,就跟注释一样,经常会抱怨别人写的代码没有写注释,然而自己写起代码起来,最讨厌的,也是写注释。所以仅仅只通过强制来规范大家是不够的,随着时间推移,版本迭代,接口文档往往很容易就跟不上代码了。
Swagger是什么?它能干什么?
Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。
Swagger整合Springboot的使用:
一、引入依赖
<!--添加Swagger依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--添加Swagger-UI依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
二、编写配置类
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.builders.RequestHandlerSelectors;
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 {
/**
* 添加摘要信息(Docket)
* .groupName("XXXX")配置这个Docket的组名
*/
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).groupName("组名:")
.apiInfo(new ApiInfoBuilder()
.title("标题:此处是配置UI界面显示的标题信息")
.description("描述:这里配置的是UI界面显示的对这个接口文档的描述信息")
.version("版本号:1.0")
.build())
.select()
//扫描Api接口的包监听是哪一个路径的
.apis(RequestHandlerSelectors.basePackage("com.test.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
}
三、监听的controller类
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ApiOperation()配置这个接口的描述信息
*/
@RestController
@RequestMapping("test")
public class TestController {
@ApiOperation("测试SwaggerApi的接口")
@RequestMapping(value = "hello",method = RequestMethod.POST)
public String test(TestReq req){
return "hello swagger";
}
}
四、入参实体类
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class TestReq {
@ApiModelProperty("用户id")
private String id;
}