1.Swagger能做什么
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。
Swagger 帮助用户、团队和企业简化API开发, 让部署管理和使用功能强大的 API 变得十分简单
2.Swagger +Springboot示例?
1.创建Springboot项目,pom.xml中增加? springfox-swagger2 和?springfox-swagger-ui 依赖,参考代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.boot</groupId>
<artifactId>demo-swagger</artifactId>
<version>1.0.0</version>
<name>demo-swagger</name>
<description>Demo project for Spring Boot + Swagger2</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
</dependencies>
</project>
2.创建Swagger配置类
package com.boot.swagger;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
//加载swagger 扫描包
.apis(RequestHandlerSelectors.basePackage("com.boot.swagger"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot+ Swagger2")
.description("")
.version("2.9.2")
.contact(new Contact("=PNZ=BeijingL", "https://blog.csdn.net/Beijing_L", "beijingL@sohu.com"))
.license("API的许可信息")
.licenseUrl("https://blog.csdn.net/Beijing_L")
.build());
}
}
3. 创建产品Product类
package com.boot.swagger;
import io.swagger.annotations.ApiModelProperty;
public class Product {
@ApiModelProperty(value = "产品id")
private Long id;
@ApiModelProperty(value = "产品名称")
private String productName;
@ApiModelProperty(value = "产品编码")
private String productCode;
//省略getter和setter
}
注解说明:
@ApiModelProperty()注解用于方法,字段,可用属性如下
- value–字段说明?
- name–重写属性名字?
- dataType–重写属性类型?
- required–是否必填?
- example–举例说明?
- hidden–隐藏
4.创建产品Controller,?遵循 restful风格
@RestController
@Api(tags = "产品管理相关接口")
@RequestMapping("/product")
public class ProductController {
/**
* Restful: 【POST】 /Products # 新建产品信息
*/
@PostMapping("/")
@ApiOperation("新建产品接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "productName", value = "产品名称", defaultValue = "测试产品"),
@ApiImplicitParam(name = "productCode", value = "产品编码", defaultValue = "99999", required = true)
}
)
public Product addProduct(String productName, @RequestParam(required = true) String productCode) {
System.out.println("do addProduct");
Product product = new Product();
product.setProductName("高清包");
product.setId(1000L);
return product;
}
/**
* Restful: 【PUT】 /Products/1001 # 更新产品信息(全部字段)
*/
@PutMapping("/{id}")
@ApiOperation("更新产品接口")
public Product updateProduct(@RequestBody Product product) {
System.out.println("do update");
return product;
}
/**
* Restful: 【GET】 /Products/1000 # 查询产品信息列表
*/
@GetMapping("/{id}")
@ApiOperation("查询产品接口")
@ApiImplicitParam(name = "id", value = "产品id", defaultValue = "99", required = true)
public Product getProduct(@PathVariable Long id) {
System.out.println("do getProductById");
Product product = new Product();
product.setId(id);
product.setProductName("基本包产品");
product.setProductCode("BASIC");
return product;
}
/**
* Restful: 【DELETE】 /Products/1001 # 删除产品信息
*/
@DeleteMapping("/{id}")
@ApiOperation("删除产品接口")
@ApiImplicitParam(name = "id", value = "产品id")
public void deleteProduct(@PathVariable Long id) {
System.out.println("do deleteProduct");
}
/**
* Restful: 【GET】 /Products # 查询产品信息列表
*/
@GetMapping("/")
@ApiOperation("查询所有产品接口")
public List<Product> getProduct() {
Product product = new Product();
product.setId(1000L);
product.setProductName("基本包产品");
product.setProductCode("BASIC");
List<Product> products = new ArrayList<>();
products.add(product);
return products;
}
}
注解说明
@Api注解,使用在类上,表明是swagger资源,@API拥有两个属性:value、tags
- value:说明该类的作用,可以在UI界面上看到
- tags :说明该类的作用,可以在UI界面上看到
@ApiOperation,使用于在方法上,表示一个http请求的操作
- value用于方法描述
- notes用于提示内容
- tags可以重新分组
@ApiImplicitParams,用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
- name:参数名
- value:参数的汉字说明、解释
- required:参数是否必须传
- paramType:参数放在哪个地方
- ? ? ? header --> 请求参数的获取:@RequestHeader
- ? ? ? query --> 请求参数的获取:@RequestParam
- ? ? ? path(用于restful接口)--> 请求参数的获取:@PathVariable
- ? ? ? body(不常用)
- ? ? ??form(不常用)
- dataType:参数类型,默认String,其它值dataType="Integer"
- defaultValue:参数的默认值
5.访问swagger-ui
浏览器中访问? ?http://localhost:8004/swagger-ui.html? 获取如下信息
?
?
?
3.参考源码
?连接:https://github.com/PNZBEIJINGL/springboot/tree/master/demo-swagger
4.常见问题
1.?Failed to start bean 'documentationPluginsBootstrapper'??nested exception is java.lang.NullPointerException
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.14.jar:5.3.
问题原因:springboot版本太高和swagger运行所版本不匹配,降低springboot版本即可
连接:解决Failed to start bean ‘documentationPluginsBootstrapper‘
2. Swagger-ui中Long类型显示为integer($int64)
问题原因:Swagger只支持6种数据类型:string,number,integer,boolean,array,object,其中number有两种类型number和 integer 。int64 表示long类型
type | format | Description | number | – | Any numbers. | number | float | Floating-point numbers. | number | double | Floating-point numbers with double precision. | integer | – | Integer numbers. | integer | int32 | Signed 32-bit integers (commonly used integer type). | integer | int64 | Signed 64-bit integers (long?type). |
?
参考:swagger官网: https://swagger.io/docs/specification/data-models/data-types/
? ?
??上一篇:SpringBoot 07 如何实现任务调度及常见问题
|