什么是Swagger
简单来说,就是规范定义了接口相关信息,可以直接通过代码自动生成接口文档并且实时同步更新,提供Web页面在线测试API。不用自己再编写接口文档,也避免了前后端联调信息不同步出现的问题。
SpringBoot整合Swagger2
要求:jdk1.8+,否则swagger2无法运行
1、新建一个SpringBoot-Web项目
2、添加Maven依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
3、编写HelloController,测试确保运行成功
4、编写配置类SwaggerConfig来配置Swagger
@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {
}
5、访问测试:http://localhost:8081/swagger-ui.html ,可以看到swagger的界面
配置Swagger
1、Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger。
public class SwaggerConfig {
@Bean //配置docket以配置Swagger具体参数
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
2、可以通过apiInfo()属性配置文档信息
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱");
return new ApiInfo(
"Swagger学习", // 标题
"学习演示如何配置Swagger", // 描述
"v1.0", // 版本
"http://terms.service.url/组织链接", // 组织链接
contact, // 联系人信息
"Apach 2.0 许可", // 许可
"许可链接", // 许可连接
new ArrayList<>()// 扩展