swagger的介绍
官网给出的描述百度翻译一下就是:使用 Swagger 开源和专业工具集简化用户、团队和企业的 API 开发。了解 Swagger 如何帮助您大规模设计和记录 API。
在前后端分离的今天,完成项目往往需要前端和后端两个团队,所以就需要团队之间有密切的交流,前端调用后端提供的api,但后端往往无法做到及时的更新api信息,因为写文档之类的太麻烦了。Swagger就能帮我们实时的更新我们的api,简化了我们的开发。
Swagger的使用
1、创建springboot项目并导入相应的依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2版本需要添加的依赖是
<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、创建相应的配置类
package com.hql.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi//注意加上这个注解,2版本的加的是@EnableSwagger2注解
public class SwaggerConfig {
@Bean//注册一个Docket对象,这个对象是Swagger规定的
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).select().build();
}
}
再写上一个Controller启动项目进行测试
package com.hql.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
在浏览器中输入地址http://localhost:8080/swagger-ui/index.html就能进入相应的页面(2版本输入的是http://localhost:8080/swagger-ui.html)
该页面存在于
配置 ApiInfo
根据ApiInfo我们可以配置一些该页面的介绍信息,点开该类的源码我们可以看见有以下属性可以配置,并且该类只给我们提供了一个默认的实现和包含所有属性的构造方法,也就是说如果想自定义,不管这些属性你有没有用到都必须赋值。
默认实现如下
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfo("hql Api Documentation",//title
"这是一个关于接口的文档",//描述
"1.0",//版本号
null,//termsOfServiceurl
new Contact("hql","",""),//与谁关联,我理解是作者信息
"Apache 2.0",//开源版本号
null,
new ArrayList<>()))
.select()
.build();
}
}
重新进入页面可以看到对应信息的更改
查找和过滤
查找
当你需要指定从哪查找api时,可以以下方法
这里我们演示的是方法上有该注解才被加载进来,可以查找不到
过滤
当你需要过滤api时可以使用以下方法
这个方法能设置组名
需要注意的是在发布版本中我们需要将Swagger禁用,需要在相应版本的配置文件中加上
注解的使用
使用注解我们可以给api,实体类或者属性,方法的参数设置描述信息,方便阅读
实体类的使用
首先创建一个实体类
public class Users {
private String name;
private Integer age;
private String address;
public Users(String name, Integer age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
.......相应的set,get,tostring方法就省略了
}
新增一个mapping
@GetMapping("/getone/{id}")
public Users getone(@PathVariable int id){
return new Users("hql",22,"shangrao");
}
重新进入页面可以看到models新增了Users,这是没加注解前的
我们给实体类加上相应的注解
注解里面可以用什么描述点进注解都有,这里就不列举了,再次进入页面可以看到我们的注解生效了
Controller类的使用
使用用重新进入页面可以看到注解生效了
api测试
使用swagger我们还可以测试接口是否能成功连接,上面我们写了个传入id返回Users的api,我们就用它来测试