目录
一,spring整合swagger2的作用
Swagger 是一组围绕 OpenAPI 规范构建的开源工具,可以帮助您设计、构建、记录和使用 REST API。主要的 Swagger 工具包括:
- Swagger Editor – 基于浏览器的编辑器,您可以在其中编写 OpenAPI 定义。
- Swagger UI – 将 OpenAPI 定义呈现为交互式文档。
- Swagger Codegen – 从 OpenAPI 定义生成服务器存根和客户端库。
- Swagger Editor Next (beta) – 基于浏览器的编辑器,您可以在其中编写和查看OpenAPI和AsyncAPI定义。
- Swagger Core – 与 Java 相关的库,用于创建、消费和使用 OpenAPI 定义。
- Swagger Parser – 用于解析 OpenAPI 定义的独立库
- Swagger APIDom – 提供单一的统一结构,用于跨各种描述语言和序列化格式描述 API
二,idea项目整合swagger2的步骤
1.引入依赖
首先需要在xml中引入swagger2的相关依赖
<!--整合swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.编写实体类和服务端口
在common里编写相关类
package com.example.yin.config;
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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.time.LocalDate;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket petApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.yin.controller"))
.paths(PathSelectors.any())
.build()
.directModelSubstitute(LocalDate.class, String.class)
//
// .genericModelSubstitutes(ResponseEntity.class).useDefaultResponseMessages(false)
.enableUrlTemplating(false)
.tags(new Tag("music-server", "音乐播放器后台服务"))
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
Contact contact = new Contact("音乐播放器后台服务", "http://www.lzzy.edu.cn/",
"jiangxuezhen@lzpu.edu.cn");
return new ApiInfoBuilder()//
.title("web应用项目音乐播放器提供的Api")//
.description("音乐播放器后台服务接口说明")//
.license("Music-Server License Version 2.0")//
.contact(contact)//
.version("2.0")//
.build();
}
}
完成对项目的配置后可以启动项目
3.本地运行项目
运行项目后在这个网站可以查看项目中的所有端口方便我们对后期的维护Swagger UIhttp://localhost:8888/swagger-ui.html
三,总结
Spring Boot 整合 Swagger2 的作用主要体现在以下几个方面:
自动生成接口文档:Swagger2 能够根据 Spring Boot 项目中的代码自动生成 RESTful API 文档,减少了手动编写和维护 API 文档的工作量。
提高开发效率:通过自动生成的文档,开发人员可以快速了解和测试各个 API 接口的功能和参数,提高了开发效率。
减少沟通成本:在前后端分离的开发模式中,Swagger2 提供的在线文档可以减少前后端的沟通成本,帮助新加入项目的同事快速上手业务。
保证文档与代码的一致性:由于文档是自动生成的,因此可以保证文档与代码的一致性,避免了文档和业务不一致的情况出现。
提供交互式文档:Swagger2 提供了交互式的文档界面,用户可以直接在页面上进行 API 的测试,无需额外的工具。
支持多种语言和框架:Swagger2 是一个规范和完整的框架,不仅支持 Java 和 Spring Boot,还支持其他多种编程语言和框架,使得其具有广泛的适用性。
促进团队协作:统一的 API 文档有助于团队成员之间的协作,特别是在大型项目中,可以确保每个人都对 API 有清晰的理解。
提升用户体验:对于使用 API 的用户来说,清晰、详细的文档可以提升他们的使用体验,帮助他们更好地理解和使用 API。