这是我参与「第三届青训营 -后端场」笔记创作活动的第2篇笔记。
最近做项目时总是用postman来测试接口,想要不用额外的软件来测试,因此来简单整合一下Swagger-UI。
1、什么是Swagger-UI
Swagger-UI是对Open-API的一种实现,随着互联网技术的发展,现在的网站架构基本都变成了:前端渲染、h后端运算,前后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要。
为了统一API格式,就产生了这些工具,可以让我们更加方便的对接前后端接口,进行数据流通。
2、怎么用Swagger-UI
2.1、导入依赖
<!--Swagger-UI API文档生产工具-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
因为我的springboot版本较低,只有2.3.6,因此用不了集成的springfox-boot-starter。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2.2、编写配置类
在使用Swagger-UI之前,我们需要配置一个配置类,我一般喜欢在springboot项目中建一个config包,然后把配置类都放在这个包下。
配置类如下:
package com.li.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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//这里改成自己的controller层的相对路径
.apis(RequestHandlerSelectors.basePackage("com.li.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI")
.description("制造预测") //自己的描述
.contact(new Contact("li", null, null))//作者自己的信息
.version("1.0")
.build();
}
}
2.3、编写controller
为了便于测试,我们写一个简单的controller
package com.li.controller;
import com.li.result.AjaxResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Hellocerr {
@RequestMapping("/hello")
public AjaxResult show(){
String hello = "Hello!!!!";
return AjaxResult.success(hello);
}
}
3、启动测试
重启服务,访问:http://localhost:8001/swagger-ui.html ,就可以看到我们的Swagger-UI界面。
然后我们点击下面的get接口,可以看到详细的接口声明,包括:
- 请求方式:
- 请求路径
- 请求参数
- 响应等信息
点击下面的try it out!还可以测试接口
效果如下所示:
其实还有很多自定义注解、自定义接口说明,大家可以自己去进行更深的学习~