Spring Boot 整合 Swagger
程序员文章站
2022-05-04 15:50:11
...
文章目录
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", "aaa@qq.com"),
"LICENSE",
"LICENSE URL",
Collections.emptyList()
);
}
}
访问方式:http://localhost:8080/swagger-ui.html
推荐阅读
-
spring boot整合mybatis+mybatis-plus的示例代码
-
spring boot tomcat jdbc pool的属性绑定
-
spring boot 使用Aop通知打印控制器请求报文和返回报文问题
-
通过spring boot 设置tomcat解决 post参数限制问题
-
Spring boot进行参数校验的方法实例详解
-
spring-boot整合ehcache实现缓存机制的方法
-
spring boot 即时重新启动(热更替)使用说明
-
使用 Spring Boot 2.0 + WebFlux 实现 RESTful API功能
-
spring boot2.0实现优雅停机的方法
-
spring boot 自定义starter的实现教程