SpringBoot2 整合 Swagger2
SpringBoot整合三板斧
第一步、引入pom
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
swagger-spring-boot-starter該專案主要利用Spring Boot的自動化配置特性來實作快速的將swagger2引入spring boot應用來生成API檔案,簡化原生使用swagger2的整合代碼,
swagger-bootstrap-ui是springfox-swagger的增強UI實作,為Java開發者在使用Swagger的時候,能擁有一份簡潔、強大的介面檔案體驗
swagger-annotations,swagger-models是因為springfox-swagger2包里有swagger-models-1.5.20.jar報錯,所以替換成1.5.22版本
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.valueOf(Long.java:803)
at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at......
看下1.5.20版本里AbstractSerializableParameter.java原始碼:
public Object getExample() {
if (this.example == null) {
return null;
} else {
try {
if ("integer".equals(this.type)) {
return Long.valueOf(this.example);
}
if ("number".equals(this.type)) {
return Double.valueOf(this.example);
}
if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {
return Boolean.valueOf(this.example);
}
} catch (NumberFormatException var2) {
LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
}
return this.example;
}
}
這里只判斷了this.example == null才回傳null,其余會去進行轉換,而空字串也會進行轉換,導致格式拋出格式化轉換例外.再來看下1.5.22版本里AbstractSerializableParameter.java原始碼:
public Object getExample() {
if (this.example != null && !this.example.isEmpty()) {
try {
if ("integer".equals(this.type)) {
return Long.valueOf(this.example);
}
if ("number".equals(this.type)) {
return Double.valueOf(this.example);
}
if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {
return Boolean.valueOf(this.example);
}
} catch (NumberFormatException var2) {
LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
}
return this.example;
} else {
return this.example;
}
}
對example同時進行了null和空值的判斷,官方也發現了自己的這個問題,我們進行相應的替換即可
第二部、配置
swagger-spring-boot-starter相關配置資訊可參考如下地址:
- 原始碼地址
- GitHub:https://github.com/dyc87112/spring-boot-starter-swagger
- 碼云:https://gitee.com/didispace/spring-boot-starter-swagger
- 使用樣例:https://github.com/dyc87112/swagger-starter-demo
- 博客:http://blog.didispace.com
- 社區:http://www.spring4all.com
swagger-bootstrap-ui相關配置資訊可參考如下地址:
官方地址:https://doc.xiaominfo.com/guide/
swagger-bootstrap-ui目前已改名了knife4j-spring-boot-starter專案正式更名為knife4j,取名knife4j是希望她能像一把匕首一樣小巧,輕量,并且功能強悍,更名也是希望把她做成一個為Swagger介面檔案服務的通用性解決方案,不僅僅只是專注于前端Ui前端.
swagger-bootstrap-ui的所有特性都會集中在
knife4j-spring-ui包中,并且后續也會滿足開發者更多的個性化需求.
swagger:
version: 1.0v # 版本號
authorization: # 全域引數
name: Authorization # 鑒權策略ID,對應 SecurityReferences ID
type: ApiKey # 鑒權策略,可選 ApiKey | BasicAuth | None,默認ApiKey
key-name: X-Token # 鑒權傳遞的Header引數
# auth-regex: ^.*$ # 需要開啟鑒權URL的正則, 默認^.*$匹配所有URL
ui-config: # 排序規則
operations-sorter: method # 按方法定義順序排序
tags-sorter: alpha # 按字母表排序
docket: # 分組配置
common:
base-package: com.xxxx.a
description: API介面檔案
title: xxx介面
contact:
name: xxx
url: https://cn.bing.com/
hq:
base-package: com.xxxx.b
description: API介面檔案
title: xxx介面
contact:
name: xxx
url: https://zc.happyloves.cn:4443/wordpress/
shop:
base-package: com.xxxx.c
description: API介面檔案
title: xxx介面
contact:
name: xxx
url: https://zc.happyloves.cn
第三步、注解
@EnableSwagger2Doc // 啟用Swagger2
@EnableSwaggerBootstrapUI //啟用swagger-bootstrap-ui
@SpringBootApplication
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
撰寫代碼
@Api(value = "https://www.cnblogs.com/Sky0914/p/DemoOne-DemoOne服務~~~~~~~~", tags = {"1-DemoOne-DemoOne服務"})
@Slf4j
@Validated
@RestController
@RequestMapping("/common/DemoOne")
public class DemoOneController {
private final DemoOneService service;
@Autowired
public DemoOneController(DemoOneService service) {
this.service = service;
}
//=====================================================================================DELETE=====================================================================================
@ApiOperation(value = "https://www.cnblogs.com/Sky0914/p/根據主鍵ID洗掉", notes = "根據主鍵ID洗掉~~~~~~~~~~~~~")
@DeleteMapping("/{id}")
public ApiMessage deleteById(@PathVariable @Min(1) int id) throws Exception {
return service.deleteById(id);
}
//=====================================================================================GET========================================================================================
@ApiOperation(value = "https://www.cnblogs.com/Sky0914/p/獲取所有資料", notes = "獲取所有資料~~~~~~~~~~~~~")
@GetMapping("/")
public ApiMessage<List<DemoOneResponse>> getAllList() {
return service.getAllList();
}
@ApiOperation(value = "https://www.cnblogs.com/Sky0914/p/根據主鍵ID獲取資料", notes = "根據主鍵ID獲取資料~~~~~~~~~~~~~")
@ApiImplicitParams(value = https://www.cnblogs.com/Sky0914/p/{
@ApiImplicitParam(name ="id", required = true, value = "https://www.cnblogs.com/Sky0914/p/主鍵ID", paramType = "path", dataType = "string"),
})
@GetMapping("/{id}/{name}")
public ApiMessage<DemoOneResponse> getById(@PathVariable @Min(1) int id, @PathVariable @AssertFalse boolean name) {
return service.getById(id);
}
//=====================================================================================POST=======================================================================================
@ApiOperation(value = "https://www.cnblogs.com/Sky0914/p/新增DemoOne資料", notes = "新增DemoOne資料~~~~~~~~~~~~~")
@PostMapping("/")
public ApiMessage<DemoOneResponse> save(@RequestBody @Valid DemoOneRequest parameter) {
return service.addDemoOne(parameter);
}
//=====================================================================================PUT========================================================================================
@ApiOperation(value = "https://www.cnblogs.com/Sky0914/p/更新DemoOne資料", notes = "更新DemoOne資料~~~~~~~~~~~~~")
@PutMapping("/")
public ApiMessage<DemoOneResponse> update(@RequestBody @Valid DemoOneRequest parameter) {
return service.update(parameter);
}
大功告成!!!啟動訪問如下地址:
Swagger2地址:
http://${ip地址}??{埠}/swagger-ui.html
swagger-bootstrap-ui地址:
http://${ip地址}??{埠}/doc.html
趙小胖個人博客:https://zc.happyloves.cn:4443/wordpress/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/119101.html
標籤:Java
上一篇:JAVA_NIO通信理論基礎
