文章目录
Why Swagger?
手写文档存在的问题
每当文档需要更新时,需要重新发送最新文档给前端,文档更新交流不及时。
接口返回结果不明确
不能直接在线测试接口,通常需要借助工具,比如:Postman
当接口文档太多时,不好分类管理
总结:前端、后段无法做到“及时协商,尽早解决”
引入Swagger相关依赖
1)、引入Spring整合Swagger依赖[SpringFox]
<!-- 引入Spring整合Swagger依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2)、编写SpringFox配置类
/**
* Spring 整合 Swagger配置类 [Docket:摘要]
* @Author MoCha
*/
@Configuration
@EnableSwagger2
public class SpringFoxConfig {
@Bean
public Docket apiDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
访问地址:http://localhost:8080/v2/api-docs
@EnableSwagger2 enables SpringFox support for Swagger 2
DocumentationType.SWAGGER_2 tells the Docket bean that we are using version 2 of Swagger specification
select() creates a builder, which is used to define which controllers and which of their methods should be included in the generated documentation
apis() defines the classes (controller and model classes) to be included. Here we are including all of them, but you can limit them by a base package, class annotations and more
paths() allow you to define which controller's methods should be included based on their path mappings. We are now including all of them but you can limit it using regex and more
3)、引入Swagger-Ui依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
4)、添加ApiInfo
@Configuration
@EnableSwagger2
public class SpringFoxConfig {
@Bean
public Docket apiDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(getApiInfo()); // 将ApiInfo加入到Docket中
}
private ApiInfo getApiInfo() {
return new ApiInfo(
"Spring Boot整合Swagger的API文档",
"关于UserController的使用说明",
"1.0.0",
"https://gitee.com/MoChaYZF",
new Contact("MoCha", "https://gitee.com/MoChaYZF", "1358192165@qq.com"),
"LICENSE",
"LICENSE URL",
Collections.emptyList()
);
}
}
访问方式:http://localhost:8080/swagger-ui.html