Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
作用:
2. 功能测试。
Swagger是一组开源项目,其中主要要项目如下:
-
Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。
-
Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。
-
Swagger-js: 用于JavaScript的Swagger实现。
-
Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。
-
Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。
-
Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码。
整合Swagger
-
maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<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>
<dependency><!-- 必须依赖-->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
-
编写swagger配置类
package com.yyl.springbootproject.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author: BruceYoung
* @date: 2023/5/6
*/
-
spring配置文件中的设置
-
swagger生成API需要用到的注解
在对映的接口方法上需要写上swagger的API注解,才能将你所写的内容生成API文档
@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明")
@ApiImplicitParam(name="参数名",value="参数具体做用",dataType="参数数据类型",
required="是否必填(true/false)",paramType="参数类型")
@ApiIgnore 勿略内容不生成API,可用于参数和方法上。
新版本的spring boot(2.6以后)中需要增加参数,否则启动报错,一定要加!!!
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
-
访问与使用
启动项目后,通过浏览器访问 http://localhost:端口号/swagger-ui.html 可看到API文档
单个方法点开后可看详细信息,右侧的Try it out,可对接口进行测试